[solved] ereg_replace - multiple instances....

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
elfling
Forum Newbie
Posts: 2
Joined: Fri Aug 19, 2005 6:56 pm

[solved] ereg_replace - multiple instances....

Post 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!
Last edited by elfling on Sat Aug 20, 2005 7:10 am, edited 1 time in total.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

preg_replace() works best for this:

Code: Select all

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

Moved to Regex.
elfling
Forum Newbie
Posts: 2
Joined: Fri Aug 19, 2005 6:56 pm

Post 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! ;)
Post Reply