In PHP I have this json string with search and replace words
$json = '[{"Original":"test1","Replacement":"test1a"},{"Original":"test2","Replacement":"test2a"}]';
Now I want to do a search and replace in a text string for all items in this json file.
$searchReplaceArray = '[{"Original":"test1","Replacement":"test1a"},{"Original":"test2","Replacement":"test2a"}]';
$text1 = 'Hello test1, let me see if test2 is also replaced...';
$text2 = str_ireplace(array_keys($searchReplaceArray), array_values($searchReplaceArray),$text1);
echo 'Original: ' . $text1 . '<br>';
echo 'Replace: ' . $text2;
I expect $text2 to be: "Hello test1a, let me see if test2a is also replaced…"
However, it does not work. Any help would be appreciated.
>Solution :
// It's not a valid Json, so you need add square brackets around it
$searchReplaceArray = '['. $json .']';
$searchReplaceArray = json_decode($searchReplaceArray, true);
// get search array
$Original = array_column($searchReplaceArray , 'Original');
// get replacement array
$Replacement = array_column($searchReplaceArray , 'Replacement');
$text1 = 'Hello test1, let me see if test2 is also replaced...';
$text2 = str_ireplace($Original, $Replacement,$text1);
echo 'Original: ' . $text1 . '<br>';
echo 'Replace: ' . $text2;
// Replace: Hello test1a, let me see if test2a is also replaced...