Re: regexp problem
| From: | xinchro | Date: | Sun, 17 Dec 2000 21:25:51 +0000 |
| Subject: | Re: regexp problem | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-30768@lists.php.net to get a copy of this message | ||
Joe Stump wrote:
>
> If all you want to do is replace a word with another use str_replace() - it's
> quite a bit faster and just the same thing.
>
> $new_string = str_replace('the','foo',$old_string);
>
> --Joe
>
> On Sun, Dec 17, 2000 at 01:56:55AM +0000, Chris Jones wrote:
> > Hi
> >
> > I'm working on simple regexp that works fine with sed, but doesn't seem
> > to work with PHP 4.0.3pl1.
> >
> > For example, I want to replace all occurances of the word "the" with
> > "foo", so I use:
> >
> > cat file.txt | sed -e "s/\Wthe\W/ foo /g"
> >
> > and it works. Translating this into php would be:
> >
> > print (egrep_replace ("\Wthe\W", " foo ", $text));
> >
> > but this just produces the original $text with nothing changed. What am I
> > doing wrong?
> >
Chris Jones wrote:
>
> Hi
>
> In article <20001216175823.B21270@zorka.com>, "Joe Stump"
> <joe@earth.care2.com> wrote:
>
> > it's quite a bit faster and just the same thing.
>
> It's not "just the same thing", the regexp "\Wfoo\W" only replaces
> "foo"
> where it's a whole word, str_replace(); would replace "foobar", which I
> don't want.
> Thanks for the suggestion anyway - fortunately I managed to fix the
> problem, I think I must have had a typo or something.
>
Hello
Perhaps this would do what you want:
<?
$text = "foo, the foobar and barfoo are -foo- while foo is not foo";
print "$text\n";
print( ereg_replace('([^[:alnum:]]|^)foo([^[:alnum:]]|$)',
'[\\1]FOO[\\2]', $text) ) . "\n";
?>
On my PHP 3.0.7 the output is (are?) :
foo, the foobar and barfoo are -foo- while foo is not foo
[]FOO[,] the foobar and barfoo are [-]FOO[-] while[ ]FOO[ ]is not[ ]FOO[]
Tell us if you found a better code :-)
Regards,
xinchro
__________________________________________________
Do You Yahoo!?
Yahoo! Shopping - Thousands of Stores. Millions of Products.
http://shopping.yahoo.com/