$string='print the imprint with the imprinted printing paper';
$pattern=array('/print/','/imprint/','/paper/',);
$replacement=array('imprint','print','machine');
输出:
print the imprint with the imprinted printing machine
我认为我理解正确,前两个模式相互覆盖。我正在考虑让它变得更复杂,但 REGEX 对我来说仍然是巫术。显示输入字符串后,我想取回它:使用打印压印机压印打印
。如果我还能看到如何让它输出 imprint the print with the imprinted printing machine
,那也太好了。
如果您能解释一下您的正则表达式,那会更有帮助。也许之后我可以自己做更多事情。
最佳答案
在一个正则表达式中完成所有这些替换,你没问题,因为在一次传递中,正则表达式将在一次替换后继续,并且不会再次尝试与替换匹配:
$string = 'print the imprint with the imprinted printing paper';
// A single array of find => replace
$replacements = array(
'print' => 'imprint',
'imprint' => 'print',
'paper' => 'machine'
);
// Dynamically form the regex, properly escaping it
$delimiter = '/';
$words = array_keys( $replacements);
$regex = $delimiter . '\b(' . implode('|', array_map( 'preg_quote', $words, array_fill( 0, count( $words), $delimiter))) . ')\b' . $delimiter;
形成的正则表达式如下所示:
/\b(print|imprint|paper)\b/
地点:
\b
是一个单词边界。()
是一个捕获组。print|imprint|paper
是一个或匹配其中一个词
最后,做替换:
$result = preg_replace_callback( $regex, function( $match) use( $replacements) {
return $replacements[$match[1]];
}, $string);
echo $result;
这will output :
imprint the print with the printed imprinting machine
关于php - 需要用自定义同义词替换文本中的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17535776/