正则表达式帮助生成链接

发布于 2024-12-03 03:29:57 字数 611 浏览 4 评论 0原文

我目前在循环中有以下代码:

$message = preg_replace("/({$data[0]})/i","<a href=\"{$data[1]}\" class=\"postlink\">$1</a>",$message,1);

该循环的要点是查找特定关键字 ($data[0]) 并将它们转换为指向 $data[1] 中 URL 的链接。我还使用了 1 的限制。

这在某种程度上可以正常工作。不过,我正在尝试改进此正则表达式,以防止出现以下问题:

  • 如果 URL 实际上包含标记的关键字,则事情会变得混乱。例如,如果“test”是关键字,并且页面有一个指向“http://www.site.com/test.html”之类的 URL 的链接,那么它将替换“test.html”,这是错误的。它应该忽略它。
  • 如果文本已经包含类似 this is a test 的内容,我不希望替换关键字“test”,因为它已经链接的一部分。

这是我到目前为止发现的两个主要问题,可能还有更多。我正在寻求帮助编写更好的正则表达式来避免这些问题。

谢谢

I currently have the following code in a loop:

$message = preg_replace("/({$data[0]})/i","<a href=\"{$data[1]}\" class=\"postlink\">$1</a>",$message,1);

The point of this loop is to look for specific keywords ($data[0]) and to turn them into links to the URL in $data[1]. I am also using a limit of 1.

This works OK to some extent. However I am trying to improve this regular expression to prevent issues such as:

  • if a URL actually contains a flagged keyword, things get messed up. For example if "test" is a keyword and the page has a link to a URL like "http://www.site.com/test.html", then it will replace "test.html" which is wrong. It should ignore it.
  • if the text already contains something like <a href="blabla">this is a test</a> , I don't want the keyword "test" to be replaced, since it's already part of a link.

Those are 2 the main issues that I've caught so far, there may be more. I'm looking for help writing a better regular expression to avoid those issues.

Thanks

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

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

发布评论

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

评论(2

私藏温柔 2024-12-10 03:29:57

这些很有趣。使用时,只需将“test”替换为下面模式中的数据即可。

/test(?![^><]*?(?:>|<\/a))/

编辑:更新了模式。

为了回复您的评论,请使用以下内容:

$message = preg_replace("/({$data[0]}(?![^><]*?(?:>|<\/a)))/i","<a href=\"{$data[1]}\" class=\"postlink\">$1</a>",$message,1);

These are fun. To use, just replace "test" with your data in the pattern below.

/test(?![^><]*?(?:>|<\/a))/

Edit: Updated the pattern.

In response to your comment, use the following:

$message = preg_replace("/({$data[0]}(?![^><]*?(?:>|<\/a)))/i","<a href=\"{$data[1]}\" class=\"postlink\">$1</a>",$message,1);
浮世清欢 2024-12-10 03:29:57

这只是检查是否有行的开头或关键字之前的空格,以及字符串的结尾或单词之后的空格:

 $message = preg_replace("/(^|\s)({$data[0]})($|\s)/mi","$1<a href=\"{$data[1]}\" class=\"postlink\">$2</a>$3",$message,1);

这应该可以解决您的两个问题。

This simply checks that there is either the begining of the line, or a space before the keyword, and an end of string, or space after the word:

 $message = preg_replace("/(^|\s)({$data[0]})($|\s)/mi","$1<a href=\"{$data[1]}\" class=\"postlink\">$2</a>$3",$message,1);

That should solve both your problems.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文