我需要將包含長網址的文本字符串轉換爲相同的字符串,但使用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
如何能不能做到?
我需要將包含長網址的文本字符串轉換爲相同的字符串,但使用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
如何能不能做到?
爲了縮短文本中任意數量的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
要回答你的如何使用的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);
謝謝我試過,但不起作用(除非我用錯了)應該echo $ textWithShortURLs返回字符串與短url? – Steven 2010-03-12 20:12:56
這是正確的。 $ textWith ...包含您的整個文本,其中包含已更改的網址。但是,我剛剛修復了腳本中的另一個錯誤。實際上,長URL是在$ matches [0]中,$ matches [1]只包含沒有http://的URL。 – 2010-03-12 20:24:45
@ the-banana-king:我修正了你的正則表達式,它有a-b而不是a-z – Erik 2010-03-12 20:37:11