我正在尝试自动检测内容中的链接并创建超链接。
我支持http
、https
和www
。
问题是,当我的正则表达式找到www
链接时,它应该在结果前面加上http://
。
我知道我可以使用str_replace()
或strpos()
等,但这能使用preg_replace()
吗?
PHP
$input = '<p>Hello, visit http://stackoverflow.com or www.stackoverflow.com</p>';
$regex_url = '~(?:(https?)://([^'s<]+)|(?:www'.[^'s<]+?'.[^'s<]+))(?<!['.,:])~i';
echo preg_replace( $regex_url, '<a href="$0" target="_blank">$0</a>', $input );
结果
<p>Hello, visit <a href="http://stackoverflow.com" target="_blank">http://stackoverflow.com</a> or <a href="www.stackoverflow.com" target="_blank">www.stackoverflow.com</a></p>
不知道如何推断每个具体情况下是否需要http://
或https://
,但使用替换回调很容易实现:
$input = '<p>Hello, visit http://stackoverflow.com or www.stackoverflow.com</p>';
$regex_url = '~(?:(https?)://([^'s<]+)|(?:www'.[^'s<]+?'.[^'s<]+))(?<!['.,:])~i';
echo preg_replace_callback( $regex_url, function($m) {
return substr($m[0], 0, 4) == "http" ?
'<a href="' . $m[0] . '" target="_blank">' . $m[0] . '</a>':
'<a href="http://' . $m[0] . '" target="_blank">http://' . $m[0] . '</a>';
}, $input);
查看IDEONE演示
在回调中,我使用substr($m[0], 0, 4) == "http"
检查匹配值。如果它以http
开始,我只使用匹配值。如果没有,我添加它。
您可以使用以下内容:
<?php
$input = '<p>Hello, visit https://stackoverflow.com or http://stackoverflow.com or www.stackoverflow.com</p>';
$regex_url = '~(?:http(s?)://|(www'.))([^'s<]+)(?<!['.,:])~i';
echo preg_replace( $regex_url, '<a href="http$1://$2$3" target="_blank">$0</a>', $input );
?>
它有点难看,因为它依赖于捕获s?
或www...