Skip to content
Advertisement

Issue with str_replace replacing the wrong values

I’m trying to replace a list of numbers (ids) with their related title, the problem is that when the title has a number also gets replaced, for example:

$idlist = "1, 2, 3";

$a = array(17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1);
$b = array('Star Trek 7', 'Superman 8', 'Toy Story 2', 'Terminator 3', 'Other', 'Superman 4', 'Star Trek 3', 'Superman 3', 'Mad Max 3', 'Mad Max 2', 'Superman 3', 'Superman 2', 'Christmas Vacation 3', 'Star Trek 2', 'Terminator 2', 'Toy Story 3', 'Mission Impossible 2');

echo str_replace($a, $b, $idlist);

Wrong current result:

Mission Impossible 2, Toy Story 3, Terminator Toy Story 3

Should be:

Mission Impossible 2, Toy Story 3, Terminator 2

What would be a better way to do this?

Advertisement

Answer

Try strtr instead str_replace:

$idlist = "1, 2, 3";

$a = array(17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1);
$b = array('Star Trek 7', 'Superman 8', 'Toy Story 2', 'Terminator 3', 'Other', 'Superman 4', 'Star Trek 3', 'Superman 3', 'Mad Max 3', 'Mad Max 2', 'Superman 3', 'Superman 2', 'Christmas Vacation 3', 'Star Trek 2', 'Terminator 2', 'Toy Story 3', 'Mission Impossible 2');

$pairs = array_combine($a, $b);

echo strtr($idlist, $pairs);

Result:

Mission Impossible 2, Toy Story 3, Terminator 2
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement