如何精确更换弦乐

时间:2015-04-02 07:31:33

标签: php

$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。是否有实现这一目标的功能?

2 个答案:

答案 0 :(得分:0)

发生这种情况是因为php首先搜索“chan”,将其替换为2个位置,然后找不到第二个字符串。首先搜索更长的字符串。

答案 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;