正则表达式找到多个不匹配的单词(否定单词匹配)

时间:2014-04-10 14:26:28

标签: php regex preg-replace

我需要每个字符串每次只允许一个特定的单词,但是存在多个有效的单词。

使用下面的正则表达式我没有得到预期的结果:

preg_replace('/\b^(true|false|TRUE|FALSE)\b/', '', 'false'); // Returns an empty string, but i expect 'false'

preg_replace('/\b^(true|false|TRUE|FALSE)\b/', '', 'test') // Returns 'test', but i expect an empty string

有人知道什么是错的?

编辑1

长输入的示例:

preg_replace('/\b^(true|false|TRUE|FALSE)\b/', '', 'This regex allow only boolean, such as true, false, TRUE and FALSE');

打印:

// This regex allow only boolean, such true, false, TRUE and FALSE

但我希望有一个空字符串,因为只有一个单词应该是一个有效的匹配

4 个答案:

答案 0 :(得分:2)

你的正则表达式对你正在做的事情是错误的。你需要消极的向前看。

试试这段代码:

$re = '/\b(?!(?:true|false|TRUE|FALSE))\w+\b/'; 
$str = 'I need true to allow only false specific FALSE words in a TRUE string'; 

$repl = preg_replace($re, "", $str);
//=>   true    false  FALSE    TRUE 

Online Demo

答案 1 :(得分:2)

不确定我是否理解您的需求,但对您来说没问题:

if (preg_match('/^(true|false|TRUE|FALSE)$/', $string, $match)) {
    echo "Found : ",$m[1],"\n";
} else {
    echo "Not found\n";
}

答案 2 :(得分:1)

在这种情况下,您不需要正则表达式,您可以使用in_array

$arr = array('true', 'false', 'TRUE', 'FALSE');

$result = (in_array($str, $arr, true)) ? $str : '';

答案 3 :(得分:0)

这是你想要的吗?

(=?)(TRUE | FALSE | TRUE | FALSE | \ S *)(?!)

Regular expression visualization

Debuggex Demo

$regex = '/(?=.)(true|false|TRUE|FALSE|\\s{0,})(?!.)/';
$testString = ''; // Fill this in
preg_match($regex, $testString, $matches);
// the $matches variable contains the list of matches
相关问题