str_replace matching characters help


#1

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

[php]<?php
// 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.

?>[/php]

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

Thanks in advance for any help!


#2

Try changing
[php]
$phrase1 = array(’/music/’,’/musical_instruments/’,’/practice/’);
[/php]
to

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

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:

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

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.


#3

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!