Search code examples
phpregexphpbb

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


Solution

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