Search code examples
phparraysreplace

Use an array of words to match and an array of replacements to perform replacements on a string


I have a problem with PHP arrays that I can't seems to find a solutions for.

Im using a str_replace to search for an array of keys, and replace it with values from another array

Example:

$findkeys = array("Key1","Key2","Key3");
$newvalues = array("Value 1","Value 2","Value 3");
$NewVal = str_replace($findkeys, $$newvalues,  "Hello, here is Key1 used");

This set the value of $NewVal to "Hello, here is Value 1 used".

This is what I want

$Data = array("Key1"=>"Value1","Key2"=>"Value2","Key3"=>"Value3");
findkeys = ##Code to get all Keys into an array## Here!!
newvalues = ##Code to get all values into an array## Here!!
$NewVal = str_replace($findkeys, $$newvalues,  "Hello, here is Key1 used");

Can/How this be be done?


Solution

  • You need to use array_keys() and array_values().

    $Data = array("Key1"=>"Value1","Key2"=>"Value2","Key3"=>"Value3");
    $NewVal = str_replace(array_keys($Data), array_values($Data),  "Hello, here is Key1 used");
    

    array_keys() will return all of the keys of an array with numeric and sequential keys as an array.

    array_values() will return all the values of an array with numeric and sequential keys as an array.