php - 需要用自定义同义词替换文本中的单词

标签 php regex

$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/

地点:

  1. \b 是一个单词边界。
  2. () 是一个捕获组。
  3. 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/

相关文章:

php - 在 PHP 中的特定值之后在数组中添加新元素?

javascript - AJAX 未将数据传递给 PHP 脚本?

javascript - 尝试使用ajax调用php函数不起作用

python - 正则表达式不匹配

C# 正则表达式匹配,但不写入值

php - 是什么阻止浏览器从同一域同时加载 2 个长时间运行的 PHP 脚本?

php - Homebrew PHP 似乎没有链接。 - 代客

javascript - 在 JavaScript 中修改 RegEx 匹配

c# - 为什么这个正则表达式在最后一场比赛中失败

java - 正则表达式分割包含特定单词的句子