php - 预匹配 : and-not expression

标签 php regex preg-match

我有一个带有换行符的文本,我需要检查它是否有一些单词,但没有另一个单词。

例如:

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

如果文本中有单词“lorem”和“ipsum”,无论在哪一行,测试都应该失败。如果文本包含“lorem”但在任何行上都没有“ipsum”,那么它应该成功。

我可能会做一些解决方法,并使用条件、explodestrpos 函数进行测试。但我想使用正则表达式规则作为预定义预设,这样我就可以轻松扩展功能。

最佳答案

您可以使用这样的正则表达式:

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/

相关文章:

php - 只能将表的最后一行数据插入到 session 中

regex - 在 Excel 单元格中调用正则表达式

python - 如何提取给定键的值?

php安全问题

php - 如何避免向每个 .html 页面添加相同的导航栏模板

php/Mysql最好的树结构

php - 如何使用 RegEx 确定分隔符之间的最大块?

php - 验证字符串是否为带有某些特殊字符的字母数字

php - 从帮助中选择 *

c# - 使用regex c#获取字符之间的字符串