Page 1 of 1

Simple regex problem

Posted: Sat Jan 28, 2006 11:04 am
by dreamline
Hi all,
I've got a fairly simple question. I've run through some tutorials but i can't seem to get the hang of preg_replace. What I wanna do is the following: I've got a large string with the same words but I only want to replace the first word it finds. Hope someone can help me.

The string i have so far is something like this:

Code: Select all

$string='I have my dream. And you have a dream too!';
echo(preg_replace('/dream/','work',$string));
What i wanna do is replace the first word dream with something like work, but the second word dream should still stay dream. Right now both words become work and i can't seem to figure out how to change only the first it encounters..

Can anybody help me? And if you know some good tutorials on regex then please post them cause i think i need them badly.. LOL

Thanks for any help though....

Posted: Sat Jan 28, 2006 11:25 am
by Ree
Try this:

Code: Select all

$string = 'I have my dream. And you have a dream too!';
echo preg_replace('/dream/', 'work', $string, 1);

Posted: Sat Jan 28, 2006 11:43 am
by dreamline
Darn, i've tried a thousand combo's, and probably i tried the one you just mentioned on an ereg_replace.. LOL...

Thanks, you da best... !!!! :D It works.... :)

Posted: Sat Jan 28, 2006 11:58 am
by Ree
Cool :)