0

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.

7
  • join the arrays into a key pair, so [200 => "David", 201 => "Rimma"] then split the $string into an array by splitting on the spaces, then just do a foreach key, value of the keypair and then replace the string if it matches the key and if it does then replace it with the value from the keypair Commented Jan 17, 2022 at 15:58
  • thats slow (my previous comment) but it works Commented Jan 17, 2022 at 15:58
  • You could use preg_replace() with word delimiters regexps in $attribute_ids Commented Jan 17, 2022 at 16:23
  • for last part how do i convert back from splited string into normal string ? @Dean Van Greunen Commented Jan 17, 2022 at 16:24
  • How did you try to use preg_replace()? Commented Jan 17, 2022 at 16:28

1 Answer 1

1

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 :)..

Sign up to request clarification or add additional context in comments.

1 Comment

if anyone will come across this what fixed the issue was simply adding "/\b" . $searched_string . "\b/" to the string you searching in preg_replace function.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.