Page 1 of 1

[solved] ereg_replace - multiple instances....

Posted: Fri Aug 19, 2005 7:24 pm
by elfling
Hi there,

I have been trying to solve my problem for a few hours now. I must be making a stupid mistake, I guess.....

I want the following text:

Code: Select all

This [b]is[/b] just [b]an example[/b] of a string
to be replaced to

Code: Select all

This <b>is</b> just <b>an example</b> of a string
I use the following code:

Code: Select all

$string = ereg_replace('\[b\]([[:graph :][:space :]]+)\[/b\]', '<b>\1</b>', $string);
(spaces in [:graph :] and [:spaces :] are intentionally, they are not in my code.)

But what happens than is that it takes the FIRST match of [ b ] and the LAST match of [ /b ] resulting in:

Code: Select all

This <b>is[/b] just [b]an example</b> of a string
My question is: what pattern should I use to make the ereg_replace function look for the SMALLEST possible match(es)? And thereby replacing BOTH my instances of the pattern? And not just the biggest possible match.

Any help on this matter is highly appreciated!

Posted: Fri Aug 19, 2005 7:41 pm
by feyd
preg_replace() works best for this:

Code: Select all

$text = preg_replace('#\[b\](.*?)\[/b\]#i', '<b>\\1</b>', $text);

Moved to Regex.

Posted: Sat Aug 20, 2005 7:08 am
by elfling
Hi feyd!

Thanks a lot for your code! It solves my problem! My code just got way smaller. I had a dirty workaround with split('\[b\]') so I could replace the parts, one-by-one. :S

And thanks for moving the thread! Those damn newbees! ;)