ramenknight
ramenknight

Reputation: 154

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?

Upvotes: 0

Views: 74

Answers (3)

Mihai Matei
Mihai Matei

Reputation: 24276

You can simply combine those 2 arrays and replace the IDs list with preg_replace_callback:

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

$result = preg_replace_callback('/(\d+)/', static function($matches) use ($array) {
    return $array[$matches[1]];
}, $idlist);

var_dump($result);

Upvotes: 1

Gander
Gander

Reputation: 1991

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

Upvotes: 1

MR Mark II
MR Mark II

Reputation: 453

Try creating id list like an array of integers:

$idlist = array(1, 2, 3);

Instead of "1, 2, 3" you can use:

array($b[0], $b[1], ... $b[n]). 

With this form, you can only replace the names in the the array $b, and the names will change in the array list automatically.

Edit:

Convert the string to an array:

$ids = explode(",", $idlist);

And you can use the array like:

$arrayNames = array($b[intval($ids[0])], $b[intval($ids[1])], ... $b[intval($ids[n])]). 

Upvotes: 0

Related Questions