Home » Php » php replace all occurances of key from array in string

php replace all occurances of key from array in string

Posted by: admin July 12, 2020 Leave a comment

Questions:

maybe this is duplicate but i did’t find good solution.

I have array

$list = Array
(
   [hi] => 0
   [man] => 1
);
$string="hi man, how are you? man is here. hi again."

It should produce $final_string = "0 1, how are you? 1 is here. 0 again."

How can I achieve it with smart way? Many thanks.

How to&Answers:

Off of the top of my head:

$find       = array_keys($list);
$replace    = array_values($list);
$new_string = str_ireplace($find, $replace, $string);

Answer:

Can be done in one line using strtr().

Quoting the documentation:

If given two arguments, the second should be an array in the form array('from' => 'to', ...). The return value is a string where all the occurrences of the array keys have been replaced by the corresponding values. The longest keys will be tried first. Once a substring has been replaced, its new value will not be searched again.

To get the modified string, you’d just do:

$newString = strtr($string, $list);

This would output:

0 1, how are you? 1 is here. 0 again.

Demo.

Answer:

preg_replace may be helpful.

<?php
$list = Array
(
    'hi' => 0,
    'man' => 1
);
$string="hi man, how are you? Man is here. Hi again.";

$patterns = array();
$replacements = array();

foreach ($list as $k => $v)
{
    $patterns[] = '/' . $k . '/i';  // use i to ignore case
    $replacements[] = $v;
}
echo preg_replace($patterns, $replacements, $string);

Answer:

$text = strtr($text, $array_from_to)

See http://php.net/manual/en/function.strtr.php