Moh*_*eri 0 php regex url preg-replace
我有一个用PHP编写的Web应用程序.我想在用户评论中找到所有网址,并将其更改为可点击的链接.我搜索了很多网站和页面,发现下面的解决方案(不幸的是我没有找到它的参考链接):
<?php
function convert($input) {
$pattern = '@(http)?(s)?(://)?(([a-zA-Z])([-\w]+\.)+([^\s\.]+[^\s]*)+[^,.\s])@';
return $output = preg_replace($pattern, '<a href="http$2://$4">$0</a>', $input);
}
?>
Run Code Online (Sandbox Code Playgroud)
这段代码完全归功于它的作者.但我发现其中有一个我无法解决的错误.
如果检测到的URL开始小号字母(无HTTPS),该HREF值不会有š性格和HTTP将变更为HTTPS,而内部的文字是正确的.
示例:
source.com >><a href="https://ource.com">source.com</a>
你有解决这个bug的任何解决方案吗?
function convert($input) {
$pattern = '@(http(s)?://)?(([a-zA-Z])([-\w]+\.)+([^\s\.]+[^\s]*)+[^,.\s])@';
return $output = preg_replace($pattern, '<a href="http$2://$3">$0</a>', $input);
}
Run Code Online (Sandbox Code Playgroud)
小智 5
function convert($input) {
$pattern = '@(http(s)?://)?(([a-zA-Z0-9])([-\w]+\.)+([^\s\.]+[^\s]*)+[^,.\s])@';
return $output = preg_replace($pattern, '<a href="http$2://$3">$0</a>', $input);
}
Run Code Online (Sandbox Code Playgroud)
这是 @splash58 老兄答案的更新,用于处理以数字而不是字母开头的 URL。例如 11hub.net 或 9gag.com
感谢splash58的精彩回答!