SGL
SGL

Reputation: 361

PHP regex find BBCode that is not surrounded by another BBCode

I'm using the following regex to find IMG bbcodes and their contents in forum posts:

~\[img(?:=[\'"]?([^,]*?)(?:,[^]\'"]+)?[\'"]?)?]([^\[]+)?\[/img]~i

This works so far, but i need to define exceptions. I must find all IMG bbcodes, which are NOT surrounded by a TT- or CODE bbcode. I'm not trying to parse BBCodes (because this is done by the forum software itself).

So i want the img bbcode from here (which is working, using the regex above):

Hello, this is an example: [img]xxx[/img] - Yay!

but not from there

[tt]this is a test [img]xxx[/img] yolo![/tt]

and not from here

[code=php]<?php
echo '[img=xxx][/img]';[/code]

Any idea, how to achieve this? I'm using PHP (just in case, that a regex-only-solution is not possible).

Upvotes: 1

Views: 130

Answers (2)

Danon
Danon

Reputation: 2973

You could also use T-Regx library

pattern('\[((?:(?!img).)*?)\](?:.*?)\[\/\1\]|\[img.*\](.*?)\[\/img\]')->test($input)

Upvotes: 1

user4160188
user4160188

Reputation: 49

you could use this pattern against the second sub-pattern for your match

\[((?:(?!img).)*?)\](?:.*?)\[\/\1\]|\[img.*\](.*?)\[\/img\]  

http://regex101.com/r/tF1tX3/2

Upvotes: 0

Related Questions