我有一个用 PHP 编写的 Web 应用程序。我想找到用户评论中的所有 URL,并将它们更改为可点击的链接。我搜索了很多网站和页面,找到了以下解决方案(不幸的是我没有再次找到它的参考链接):
<?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);
}
?>
感谢其作者,该代码可以完美运行。但我发现其中有一个我无法解决的错误。
如果检测到的 URL 开头为s信函(不含 https),href价值不会有那个s性格和http将更改为https,而内部文本是正确的。
Example:
来源网>><a href="https://ource.com">source.com</a>
您有什么解决方案来解决这个错误吗?
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);
}
demo https://www.regex101.com/r/oZ1uG6/3
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)