我写了一个简单的函数,它可以接受一段文本,从中提取URL,并将所有的URL替换为带有
例如:
<a href>
标签的链接。例如:
http://site.com
应该变成<a href="http://site.com">http://site.com</a>
代码:function parseUrls( $string )
{
$string = trim($string);
$pattern = '%\bhttp[s]?://[A-z0-9/\.\-_]+%i';
$replacement = '<a href="$1">$1</a>';
$string = preg_replace($pattern, $replacement, $string);
return $string;
}
然而,如果我把以下字符串作为输入:
hello https://google.com test http://test.com/something.html abc http://site.com
我得到的输出是:
hello <a href=""></a> test <a href=""></a> abc <a href=""></a>
也就是说,URL已经被匹配,但$replacement
没有被正确应用。可能我的$1
的使用方式有误?
我做错了什么?