我有一个关联数组,其中键是搜索字符串,值是替换字符串。
$list = ['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);
preg_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);
$text = strtr($text, $array_from_to)