【发布时间】:2020-12-28 19:10:15
【问题描述】:
我有带链接的字符串,我打算将链接提取到数组中,如下所示
$string = "The text you want to filter goes here. http://google.com, https://www.youtube.com/watch?v=K_m7NEDMrV0,https://instagram.com/hellow/";
preg_match_all('#\bhttps?://[^,\s()<>]+(?:\([\w\d]+\)|([^,[:punct:]\s]|/))#', $string, $match);
print_r($match[0]);
结果
Array (
[0] => http://google.com
[1] => https://www.youtube.com/watch?v=K_m7NEDMrV0
[2] => https://instagram.com/hellow/
)
现在我将使用bit.ly API 函数gobitly() 来缩短以array 结尾的链接
foreach ($match[0] as $link){
$links[] = gobitly($link);
}
$links[]的结果
Array (
[0] => http://t.com/1xx
[1] => http://t.com/z112
[2] => http://t.com/3431
)
现在我想重建string 并替换指向新链接的链接,就像这样
$string = "The text you want to filter goes here. http://t.com/1xx, http://t.com/z112,http://t.com/3431";
【问题讨论】:
-
请注意
\w也匹配\d所以这部分[\w\d]+可以只是\w+和[:punct:]也匹配一个逗号。 -
请注意:我过去使用的至少两个第三方缩短服务已不复存在。彻底退休。如果我做了类似上述的事情,并且服务消失了,你最终会有点腐烂。如果您不记录原始网址,则您没有追索权。另一种方法是使用您自己的起酥油服务。
标签: php regex url preg-replace-callback