如何使用 preg_replace 生成正确的 URL

发布于 2024-11-18 00:17:37 字数 460 浏览 2 评论 0原文

我正在尝试找到 preg_replace 的模式,它将匹配段落中格式不正确的 HTML 链接/URL,并将其替换为正确的链接。我真的不知道如何开始。

这就是我需要形成 URL 的方式(需要包含 http://):

<a href="http://www.example.com" target="_blank">www.example.com</a>

错误的 URL 很可能以以下形式出现:

example.com
www.example.co.uk
<a href="example.com">example.com</a>
<a href=example.com>example.com</a>

任何帮助或建议将不胜感激。

谢谢,

eb_dev

I'm trying to find a pattern for preg_replace which will match incorrectly formed HTML links / URLs in a paragraph and replace them with correct links. I'm really not sure how to start with it.

This is how I need the URL to be formed (http:// needs to be included):

<a href="http://www.example.com" target="_blank">www.example.com</a>

Bad URLs may well come in the form of:

example.com
www.example.co.uk
<a href="example.com">example.com</a>
<a href=example.com>example.com</a>

Any help or advise would be greatly appreciated.

Thanks,

eb_dev

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

远昼 2024-11-25 00:17:37

好的,找到了一个似乎效果很好的解决方案:

$msg = preg_replace(
                   "#(^|[\n ])([\w]+?://[^ \"\n\r\t<]*)#is",
                   "$1<a href=\"$2\" target=\"_blank\">$2</a>",
                   $msg
                   );

$msg = preg_replace(
                   "#(^|[\n ])((www|ftp)\.[^ \"\t\n\r<]*)#is",
                   "$1<a href=\"http://$2\" target=\"_blank\">$2</a>",
                   $msg
                   ); 

Ok found a solution that seems to work pretty well:

$msg = preg_replace(
                   "#(^|[\n ])([\w]+?://[^ \"\n\r\t<]*)#is",
                   "$1<a href=\"$2\" target=\"_blank\">$2</a>",
                   $msg
                   );

$msg = preg_replace(
                   "#(^|[\n ])((www|ftp)\.[^ \"\t\n\r<]*)#is",
                   "$1<a href=\"http://$2\" target=\"_blank\">$2</a>",
                   $msg
                   ); 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文