2010-03-12 91 views
3

我需要将包含长网址的文本字符串转换为相同的字符串,但使用tinyurl(使用tinyurl api)。例如。转换在PHP中如何使用preg替换将网址变成tinyurl

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

blah blah blah http://tinyurl.com/yaeocnv blah blah blah 

如何能不能做到?

回答

3

为了缩短文本中任意数量的URL,请将API内容放在一个函数中,该函数使用长URL并返回短URL。然后通过PHP的preg_replace_callback函数将此函数应用于您的文本。这将是这个样子:

<?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; 

?> 

不要在模式算太多,只写上即时没有任何测试,也许别人可以帮助。 见http://php.net/preg-replace-callback

+0

谢谢我试过,但不起作用(除非我用错了)应该echo $ textWithShortURLs返回字符串与短url? – Steven 2010-03-12 20:12:56

+0

这是正确的。 $ textWith ...包含您的整个文本,其中包含已更改的网址。但是,我刚刚修复了脚本中的另一个错误。实际上,长URL是在$ matches [0]中,$ matches [1]只包含没有http://的URL。 – 2010-03-12 20:24:45

+0

@ the-banana-king:我修正了你的正则表达式,它有a-b而不是a-z – Erik 2010-03-12 20:37:11

0

要回答你的如何使用的preg_replace做这个问题,你可以使用e modifyer。

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