Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex how to look ahead and see if there is another matching end part?

I am using a regex pattern to find instances of [code][/code] BB tags. (This is in PHP with pearl-type regex using preg_match / preg_relace / etc)

'~\[code\](.*?)\[\/code\]~is'

Well, my question is how can I make it so somebody could type something like:

[code][code]code here[/code][/code]

The purpose of typing this would be to demonstrate to a newbie how to place their code into [code][/code] tags.

Currently if I type that, the regex will stop at the 1st instance of "[/code]" and not keep looking ahead to see the 2nd instance of "[code]"

I can't post images since I'm a new user, but here is a screenshot of the output: https://i.sstatic.net/7gS6x.png

I know there is a term in regex called "positive look ahead" and "negative look ahead", but I'm not quite sure what they mean, or if they are relevant to my situation. Could someone please give me a hand? Thank you.

EDIT: I'm sorry but I don't seem to have enough rep to +1 anything. I really appreciate your help, and it was so fast.

like image 800
Lakey Avatar asked Feb 02 '26 06:02

Lakey


1 Answers

you can try for this pattern

'~\[code\](.*?)(\[\/code\])+~is'
like image 118
WordsWorth Avatar answered Feb 03 '26 20:02

WordsWorth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!