也许这是重复的问题,但我没有找到好的解决方案。
我有一个数组
$list = Array
(
[hi] => 0
[man] => 1
);
$string="hi man, how are you? man is here. hi again."
它应该产生 $final_string = "0 1, how are you? 1 is here. 0 again."
我该如何以聪明的方式实现它?非常感谢。
也许这是重复的问题,但我没有找到好的解决方案。
我有一个数组
$list = Array
(
[hi] => 0
[man] => 1
);
$string="hi man, how are you? man is here. hi again."
它应该产生 $final_string = "0 1, how are you? 1 is here. 0 again."
我该如何以聪明的方式实现它?非常感谢。
就我个人的想法:
$find = array_keys($list);
$replace = array_values($list);
$new_string = str_ireplace($find, $replace, $string);
$keys
应该是 $replace
。 - srainstr_ireplace()
来轻松解决这个问题。 - John Conde$replace = array_values($list);
这个调用 array_values
的操作是不必要的,你可以直接将 $list
数组传递给 str_replace
函数。 - Matthewpreg_replace
可能会有帮助。
<?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);