我弄清楚了如何检查 OR 情况,preg_match( "/(word1|word2|word3)/i", $string );
。我不知道如何匹配 AND 案例。我想检查字符串是否包含所有术语(不区分大小写)。
最佳答案
可以使用前瞻在单个正则表达式中进行 AND 匹配,例如:
preg_match('/^(?=.*word1)(?=.*word2)(?=.*word3)/i', $string)
但是,在正则表达式之外执行此操作可能更清晰、更快:
preg_match('/word1/i', $string) && preg_match('/word2/i', $string) && preg_match('/word3/i', $string)
或者,如果您的目标字符串像 word1
一样简单:
stripos($string, 'word1')!==FALSE && stripos($string, 'word2')!==FALSE && stripos($string, 'word3')!==FALSE
关于php - 如何在 PHP 中使用正则表达式匹配所有术语?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1992449/