I need to convert a string of text containing a long url int开发者_如何学Goo the same string but with a tinyurl (using the tinyurl api). eg. convert
blah blah blah http://example.com/news/sport blah blah blah
into
blah blah blah http://tinyurl.com/yaeocnv blah blah blah
How can it be done?
In order to shorten an arbitrary number of URLs in your text, put the API stuff in a function which takes the long URL and returns the short URL. Then apply this function via PHP's preg_replace_callback
function to your text. This would look something like this:
<?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;
?>
Don't count on that pattern too much, just wrote it on-the-fly without any testing, maybe someone else can help. See http://php.net/preg-replace-callback
To answer your question of how to do this with preg_replace, you can use the 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);
精彩评论