preg_replace doesn't do anything?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
webcan
Forum Commoner
Posts: 66
Joined: Tue Oct 28, 2003 2:25 pm
Location: Toronto, Canada

preg_replace doesn't do anything?

Post by webcan »

Can someone tell me why this doesn't do anything?

[Admin Edit: changed tags to tags][/color][/size]

Code: Select all

$speakerlist = "John Abrams+& Lucille Travis";

preg_replace("/ /", "+", $speakerlist);
preg_replace("/\046/", "and", $speakerlist);
(The second one searches for ampersands)

No changes are made to $speakerlist.

Thanks,
Peter.
User avatar
twigletmac
Her Royal Site Adminness
Posts: 5371
Joined: Tue Apr 23, 2002 2:21 am
Location: Essex, UK

Post by twigletmac »

You need to capture the returned value from the preg_replace() into the $speakerlist variable:

Code: Select all

$speakerlist = preg_replace("/ /", "+", $speakerlist);
$speakerlist = preg_replace("/\046/", "and", $speakerlist);
On a side note, instead of multiple preg_replace() calls you can do one using arrays:

Code: Select all

$string_from = array('/ /', '/\046/');
$string_to = array('+', 'and');

$speakerlist = preg_replace($string_from, $string_to, $speakerlist);
Mac
redmonkey
Forum Regular
Posts: 836
Joined: Thu Dec 18, 2003 3:58 pm

Post by redmonkey »

I see no need to envoke the regex engine for this case. Therefore str_replace would be a more appropriate function for this application.
User avatar
twigletmac
Her Royal Site Adminness
Posts: 5371
Joined: Tue Apr 23, 2002 2:21 am
Location: Essex, UK

Post by twigletmac »

redmonkey wrote:I see no need to envoke the regex engine for this case. Therefore str_replace would be a more appropriate function for this application.
Doh, totally missed that very obvious point :oops:.

Mac
Post Reply