我有一个带有换行符的文本,我需要检查它是否有一些单词,但没有另一个单词。
例如:
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
如果文本中有单词“lorem”和“ipsum”,无论在哪一行,测试都应该失败。如果文本包含“lorem”但在任何行上都没有“ipsum”,那么它应该成功。
我可能会做一些解决方法,并使用条件、explode 和 strpos 函数进行测试。但我想使用正则表达式规则作为预定义预设,这样我就可以轻松扩展功能。
最佳答案
您可以使用这样的正则表达式:
lorem[\s\S]*ipsum|ipsum[\s\S]lorem
<强> working demo
$re = "/lorem[\\s\\S]*ipsum|ipsum[\\s\\S]lorem/i";
$str = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";
if (!preg_match($re, $str, $matches)) {
// your code here
}
更新:您可以在不否定 preg_match 的情况下实现相同的效果,如 Jonathan Kuhn 在他的评论中指出:
Also, if you wanted to make this work without needing to negate the preg_match you could wrap it in a zero-width negative group like:
^(?!lorem[\s\S]*ipsum|ipsum[\s\S]lorem).*$
. This will match the entire string where both words don't exist. Demo (shows as not matching until you remove one of the words).
关于php - 预匹配 : and-not expression,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29661924/