0

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.

3
  • 2
    I would have converted the JSON using json_decode() and gone from there, but its not valid JSON Commented Feb 6, 2022 at 12:07
  • Okay, so I changed the json string into [{"Original":"test1","Replacement":"test1a"},{"Original":"test2","Replacement":"test2a"}]. And then I used json_decode to get a PHP array. When dumping , I get this: array(2) { [0]=> array(2) { ["Original"]=> string(5) "test1" ["Replacement"]=> string(6) "test1a" } [1]=> array(2) { ["Original"]=> string(5) "test2" ["Replacement"]=> string(6) "test2a" } } Commented Feb 6, 2022 at 12:15
  • json_decode($json, true) to get pho array Commented Feb 6, 2022 at 12:32

1 Answer 1

1
// 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...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.