正则表达式帮助生成链接
我目前在循环中有以下代码:
$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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这些很有趣。使用时,只需将“test”替换为下面模式中的数据即可。
编辑:更新了模式。
为了回复您的评论,请使用以下内容:
These are fun. To use, just replace "test" with your data in the pattern below.
Edit: Updated the pattern.
In response to your comment, use the following:
这只是检查是否有行的开头或关键字之前的空格,以及字符串的结尾或单词之后的空格:
这应该可以解决您的两个问题。
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:
That should solve both your problems.