开发者

Regular expression help generate links

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


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);


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜