使用regex模式变量preg_match


Using regex pattern variable with preg_match

我尝试了preg_match中其他正则表达式问题的建议解决方案,但无济于事。

$match = '/^(.|a|an|and|the|this|at|in|or|of|is|for|to|its|as|by)'$/';
$filteredArray = array_filter($wordArray, function($x){
return !preg_match($match,$x);
});

当我包含字符串文字时,它可以工作,但我想使用一个变量,以便我可以添加更多的单词。

$filteredArray = array_filter($wordArray, function($x){
return !preg_match("/^(.|a|an|and|the|this|at|in|or|of|is|for|to|its|as|by)$/",$x);
});

谢谢你的帮助!

由于变量的作用域,这不起作用。你不能从这个函数访问变量$match。

使用全局变量的解决方案。它们可以从任何地方访问。

$GLOBALS['word_regex'] = '/^(.|a|an|and|the|this|at|in|or|of|is|for|to|its|as|by)'$/';
$filteredArray = array_filter($wordArray, function($x){
return !preg_match($GLOBALS['word_regex'],$x);
});

应该可以

为什么是regexp?为什么不是!in_array($x, $forbiddenWordsArray) ?这样,更容易动态地管理元素。

匿名函数不会自动从封闭作用域捕获变量。您需要使用use声明显式地执行此操作:

$shortWords = '/^(.|a|an|and|the|this|at|in|or|of|is|for|to|its|as|by)'$/';
$filteredArray = array_filter($wordArray, 
                              function($x) use ($shortWords) {
                                  return !preg_match($shortWords,$x);
                              });