Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I do a search and replace in a PHP string based on values in a JSON string?

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…"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading