问题说明
我需要将包含长URL的文本字符串转换为相同的字符串,但带有TinyURL(使用TinyURL API)。例如。转换
blah blah blah http://example.com/news/sport blah blah blah
进入
blah blah blah http://tinyurl.com/yaeocnv blah blah blah
如何做到这一点?
api
为了缩短文本中任意数量的URL,请将正确答案放在一个函数中,该函数接受长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;
?>
不要太依赖该模式,只是在没有任何测试的情况下即时编写它,也许其他人可以提供帮助。 请参见/link?link=http://php.net/preg-replace-callback
本文出至:学新通技术网
本站名称:
学新通技术网
版权声明:本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
联系方式:luke.wu@swvq.com
标签: