![](/img/trans.png)
[英]Using variable as a part of a pattern in preg_match not working for spacial characters
[英]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);
});
感谢您的帮助!
为什么使用正则表达式? 为什么不!in_array($x, $forbiddenWordsArray)
通过这种方式,更容易进行动态管理元素。
由于变量作用域,这不起作用。 您不能从该函数访问变量$ 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);
});
那应该工作
匿名函数不会自动从封闭范围内捕获变量。 您需要使用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);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.