Reputation: 329
i have 2 arrays and a string:
$attribute_ids = array(200,201);
$attribute_names = array("David","Rimma");
$string = "200 2006-2009 boy, 201 girl";
$string = str_replace($attribute_ids, $attribute_names, $string);
output is "David David6-David9 boy, Rimma girl "
expected is "David 2006-2009 boy, Rimma girl "
issue is when array contains 200 and string contains 2000 str_replace replace the string 200 inside 2000.
im trying to replace only the exact same string that is given inside the array "$attribute_ids".
i have tried preg_replace
but it did not work.
Upvotes: 0
Views: 454
Reputation: 779
Telling the difference between whole words and parts of a word sounds like a task for regexp, so here's my take(To be specific: Add regexp word boundaries \b for the patterns):
$attribute_ids = array(200,201);
$attribute_names = array("David","Rimma");
$string = "200 2006-2009 boy, 201 girl";
echo preg_replace(
array_map(fn($item) => "/\b$item\b/", $attribute_ids),
$attribute_names,
$string
); // David 2006-2009 boy, Rimma girl
I'm not sure whether the mapping should be done outside or inside the call to array_map()
. As it is now the code is kind of confined to whole word patterns. But on the other hand, if that's ok for the task at hand or the array of patterns is huge then it could be useful :)..
Upvotes: 1