正则表达式在常用单词删除模式中忽略带连字符的单词

时间:2011-02-09 15:27:27

标签: php regex preg-replace

我有这个正则表达式从字符串($commonWords)中删除常用单词($input),我想调整它以便忽略带连字符的单词,因为这些单词有时包含常用单词

return preg_replace('/\b('.implode('|',$commonWords).')\b/i','',$input);

感谢

3 个答案:

答案 0 :(得分:2)

尝试

return preg_replace('/(?<!-)\b('.implode('|',$commonWords).')\b(?!-)/i','',$input);

这会将negative lookaround表达式添加到正则表达式的开头和结尾,这样只有在匹配之前或之后没有短划线时才允许匹配。

答案 1 :(得分:0)

preg_replace('/\b('.implode('|',$commonWords).'|\w-\w)\b/i','',$input);

\ w任何单词字符(字母,数字,下划线) 它会删除所有常用词,以及所有使用hyphene的词。

答案 2 :(得分:0)

return preg_replace('/(?<![-\'"])\b('.implode('|',$commonWords).')\b(?![-'"])i','',$input);

如果我们有更多要转义的符号,上述内容将会有效。

相关问题