在php中,如何使用preg replace将url转换为tinyurl

在php中,如何使用preg replace将url转换为tinyurl,php,replace,pcre,Php,Replace,Pcre,我需要将包含长url的文本字符串转换为相同的字符串,但使用tinyurl(使用tinyurl api)。转化 blah blah blah http://example.com/news/sport blah blah blah 进入 如何做到这一点?为了缩短文本中任意数量的URL,请将API内容放入一个函数中,该函数接受长URL并返回短URL。然后通过PHP的preg\u replace\u回调将此函数应用于文本。这看起来像这样: <?php function shorten_url

我需要将包含长url的文本字符串转换为相同的字符串,但使用tinyurl(使用tinyurl api)。转化

blah blah blah http://example.com/news/sport blah blah blah
进入


如何做到这一点?

为了缩短文本中任意数量的URL,请将API内容放入一个函数中,该函数接受长URL并返回短URL。然后通过PHP的
preg\u replace\u回调将此函数应用于文本。这看起来像这样:

<?php

function shorten_url($matches) {
    // EDIT: the preg function will supply an array with all submatches
    $long_url = $matches[0];

    // API stuff here...
    $url = "http://tinyurl.com/api-create.php?url=$long_url";
    return file_get_contents($url);
}

$text = 'I have a link to http://www.example.com in this string';

$textWithShortURLs = preg_replace_callback('|http://([a-z0-9?./=%#]{1,500})|i', 'shorten_url', $text);
echo $textWithShortURLs;

?>

不要太依赖这个模式,只需在没有任何测试的情况下动态编写它,也许其他人可以提供帮助。
请参见

要回答有关如何使用preg_replace执行此操作的问题,您可以使用
e
修改器

function tinyurlify($href) {
 return file_get_contents("http://tinyurl.com/api-create.php?url=$href");
}
$str = preg_replace('/(http:\/\/[^\s]+)/ie', "tinyurlify('$1')", $str);

谢谢,我试过了,但是没有用(除非我用错了),应该回显$textwithshorturs返回带有短url的字符串吗?这是正确的$用…发短信。。。包含您的全文,其中包含更改的URL。然而,我的脚本中还有一个错误,我刚刚修复了这个错误。实际上,长URL在$matches[0]中,$matches[1]只包含没有http:///的URL。@香蕉王:我修复了你的正则表达式,它有a-b而不是a-z@TBK:我还用我的代码中的正确位更新了你的代码,并删除了我的答案+感谢你理解了他的意思:)谢谢!它工作得很好。还有一个问题…有没有一种方法可以让URL只在字符串长度超过100个字符时被缩短?
function tinyurlify($href) {
 return file_get_contents("http://tinyurl.com/api-create.php?url=$href");
}
$str = preg_replace('/(http:\/\/[^\s]+)/ie', "tinyurlify('$1')", $str);