preg_replace("/\[b\](.*)\[\/b\]/Usi", "<strong>$1</strong>", "Some text here... [b][b]Hello, [b]PHP![/b][/b][/b] ... [b]and here[/b]");
returns
Some text here... <strong>[b]Hello, [b]PHP!</strong>[/b][/b] ... <strong>and here</strong>
But i need to replace all [b]...[/b] tags. Why this doesn't happen in my case?
Why use regex for this particular case? You could get away with a simple string replace every [b] to strong and every [/b] to the /strong.
Yes, a multi-pass approach is required if the elements are nested. This can be accomplished in one of two ways; matching from the inside out or from the outside in. Here are two tested scripts with fully commented regexes which illustrate each technique:
1. Replace from the inside out:
Output:
2. Replace from the outside in:
Output:
Note the
(?R)
recursive expression used in the second approach.The reason it doesn't work: You catch the first [b], then move on to the next [/b], and leave anything in between unchanged. Ie, you change the outer [b] tags, but not the ones nested inside.
Your comment to @meza suggests you want to replace the pseudo tags in pairs, or else leave them untouched. The best way to do this is to use multiple passes, like this
I'm not even sure if you can do it in a one-line regex, but even if you could, it would be rather complex and therefore hard to maintain.
edit your modifiers
Usi
and replace it withsim
.EDIT:
Give this a shot: