php replace all occurances of key from array in st

2020-07-10 07:05发布

问题:

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.

回答1:

Off of the top of my head:

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


回答2:

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.



回答3:

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);


回答4:

$text = strtr($text, $array_from_to)

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



标签: php replace