Simple regex problem

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

Moderator: General Moderators

Post Reply
dreamline
Forum Contributor
Posts: 158
Joined: Fri May 28, 2004 2:37 am

Simple regex problem

Post 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....
Ree
Forum Regular
Posts: 592
Joined: Fri Jun 10, 2005 1:43 am
Location: LT

Post 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);
Last edited by Ree on Sat Jan 28, 2006 11:56 am, edited 1 time in total.
dreamline
Forum Contributor
Posts: 158
Joined: Fri May 28, 2004 2:37 am

Post 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.... :)
Ree
Forum Regular
Posts: 592
Joined: Fri Jun 10, 2005 1:43 am
Location: LT

Post by Ree »

Cool :)
Post Reply