$string = 'I am chan, my son is chan_junior';
$search = array('chan', 'chan_junior');
$replace = array('a', 'b');
$new = str_replace($search, $replace, $string);
echo $new;
我想将字符串替换为I am a, my son is b
,但结果为I am a, my son is a_junior
。是否有实现这一目标的功能?
答案 0 :(得分:0)
答案 1 :(得分:0)
这有效:
$string = 'I am chan, my son is chan_junior';
$search = array('chan', 'chan_junior');
$replace = array('a', 'b');
$str_arr = explode(' ', $string);
$count = count($str_arr);
for ($i = 0; $i < $count; $i ++)
{
$word = preg_replace('/^[^A-Za-z0-9\-]*|[^A-Za-z0-9\-]*$/', '', $str_arr[$i]);
if (in_array($word, $search))
{
$key = array_search($word, $search);
$str_arr[$i] = str_replace($word, $replace[$key], $str_arr[$i]);
}
}
$new = implode(' ', $str_arr);
echo $new;