Search code examples
phpregexforumbbcode

PHP Regex to match words outside oh [URL] and [IMG] BBCode?


hoping someone can help me. I am making a PHP plugin for my forum. The goal is whenever someone types the word Amazon in a post it will automatically turn it into a link to Amazon.

I need to edit the text as it is saved in the database, before it has been converted to HTML and is still in BBCode format.

Example Text:

I really like shopping at Amazon. Here is a link: [URL="http:www.amazon.com"]Link to Amazon[URL] and here is an image: [img]http://images.amazon.com/amazon/image/zzz.jpg[/img]. Here is one more simple link: [url]http://www.amazon.net[/url]. Remember, Amazon is awesome!

--

In the above example only the very first and very last instance of "Amazon" should be matched, all the others need to be ignored.

I tried to alter a regex that does something similar except in HTML tags but no luck.

Any help would be appreciated.


Solution

  • Working it out, this seems to work-

    Amazon(?![^\[]*(\[/url]|"]|\[/img]))
    

    This will skip Amazon in any URL tag (long or short) and all IMG tags.