str_replace matching characters help

I’m having trouble using str_replace when it comes across two words that contain similar characters.

For instance, is the words “music” and “musical instruments” are in the array, str_replace will only replace the the second variable up to the point the first variable stopped.

When str_replace sees “music” in “musical instruments”, it changes it to the undesired value

// This should say - You should play stupid, dumber, and wig-out every day.

$phrase = “You should play music, musical instruments, and practice every day.”;
$phrase1 = array(’/music/’,’/musical_instruments/’,’/practice/’);
$phrase2 = array(‘stupid’,‘dumber’,‘wig-out’);

$newphrase = preg_replace($phrase1, $phrase2, $phrase);
echo $newphrase;

// Instead it returns - You should play stupid, stupidal instruments, and wig-out every day.


Is there a way to make it recognize the difference between the two different words?

Thanks in advance for any help!

Try changing
$phrase1 = array(’/music/’,’/musical_instruments/’,’/practice/’);

// Note the SPACE after music
$phrase1 = array(’/music /’,’/musical_instruments/’,’/practice/’);

I don’t use the preg_replace that much but I know in other regular expressions you need to escape a space that you are searching for so it might have to be:

$phrase1 = array(’/music /’,’/musical_instruments/’,’/practice/’);

Beecause musical would also match music, it matched that first before it matched musical_instruments, thus when it went to match musical_instruments, it had changed to stupidal_instruments and now there is no match.

Perhaps you could move musical_instruments first as well.

Anyway, there are a couple of things to try.

Thanks peg110!

The best option for me was to change the order of “musical” and it worked out great!

I didn’t realize until I returned here, that the code I had pasted wasn’t correct . I had been testing str_replace and preg_replace and posted incorrect code with some typos included :lol:

Thanks for your help!

Sponsor our Newsletter | Privacy Policy | Terms of Service