试题
$words = array(
'我'=>'你',
'不错'=>'很好',
'cc'=>'XXX',
);
$str = '你和我今天很好,XXX,是不是不错';
替换后结果 我和你今天不错,cc,是不是很好
(近义词可能是任意词语,给定的数组的键替换成值,值替换成键)
解决方案
参考代码:
<?php
$words = array(
'我'=>'你',
'不错'=>'很好',
'cc'=>'XXX',
);
$str = '你和我今天很好,XXX,是不是不错';
$words = array_merge($words, array_flip($words));
$regex = "/" . implode('|', array_map(function($word) {
$word = "(" . str_replace(['"'], [''], json_encode($word)) . ")";
$word = preg_replace("/\\\u(.{4})/", "\x{\$1}", $word);
return $word;
}, array_keys($words))) . "/u";
echo preg_replace_callback($regex, function($matches) use ($words) {
$keyword = end($matches);
return $words[$keyword];
}, $str);