php数据双向替换

$words = ['我'=>'你','不错'=>'很好','cc'=>'xxx'];
$words=array_merge($words,array_flip($words));

$str = '你和我今天很好,xxx,是不是不错';
foreach ($words as $key => $row) {
    $str=str_replace($key,"|||".$key."|||", $str);
}
$str=trim($str,"|||");
$strArr=explode("|||", $str);
print_r($strArr);
foreach ($strArr as $key => $row) {
    if (in_array($row,array_keys($words))) {
        $strArr[$key]=$words[$row];
    }
}
echo implode("",$strArr);

运行结果:

我和你今天不错,cc,是不是很好

你可能感兴趣的:(php数据双向替换)