PHP 反向 Preg_match

标签 php regex if-statement preg-match reverse

<分区>

if(preg_match("/" . $filter . "/i", $node)) {
    echo $node;
}

这段代码过滤一个变量来决定是否显示它。 $filter 的一个示例条目是“office”或“164(.*)976”。

想知道有没有简单的说法:如果$filter在$node中不匹配。以正则表达式的形式?

所以...不是“if(!preg_match”,而是 $filter = “!office” 或 “!164(.*)976”,但它有效吗?

最佳答案

如果您确定要使用“负正则表达式”而不是简单地反转正则表达式的结果,则可以这样做:

if(preg_match("/^(?:(?!" . $filter . ").)*$/i", $node)) {
    echo $node;
}

如果字符串不包含 $filter 中的正则表达式/子字符串,将匹配该字符串。

说明:(以office为例)

^          # Anchor the match at the start of the string
(?:        # Try to match the following:
 (?!       # (unless it's possible to match
  office   # the text "office" at this point)
 )         # (end of negative lookahead),
 .         # Any character
)*         # zero or more times
$          # until the end of the string

关于PHP 反向 Preg_match,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5704061/

相关文章:

PHP 版本采用统计数据?

javascript - Wordpress update_user_meta onclick 使用 Ajax

javascript - 如何捕获可能被空格包围或不被空格包围的整个单词

javascript - 更改 javascript 中输入的匹配文本的文本颜色

php - if (x > 0) outputing 0 如何什么都不输出?

linux - Perl 目录查找器不起作用?

PHP——自动 SQL 注入(inject)保护?

PHP,生成带格式的字符串,检查 SQL 数据库?

java - 在 Java 中使用正则表达式验证字符串是否包含模式

c - C 中的 If/Else 语句不起作用