PHP in_数组通配符匹配
我正在数组中存储禁止使用的单词列表:PHP in_数组通配符匹配,php,Php,我正在数组中存储禁止使用的单词列表: $bad = array("test"); 我使用以下代码对照用户名进行检查: if (in_array ($username, $bad)) { //deny } 但是我有一个问题,它只会拒绝给定的用户名是否为test,但我希望它也会拒绝给定的用户名是否为test,或者test,或者thisisatestok,或者thisisatestok 可能吗 $example = array('An example','Another example','One
$bad = array("test");
我使用以下代码对照用户名进行检查:
if (in_array ($username, $bad))
{
//deny
}
但是我有一个问题,它只会拒绝给定的用户名是否为test,但我希望它也会拒绝给定的用户名是否为test,或者test,或者thisisatestok,或者thisisatestok
可能吗
$example = array('An example','Another example','One Example','Last example');
$searchword = 'last';
$matches = array();
foreach($example as $k=>$v) {
if(preg_match("/\b$searchword\b/i", $v)) {
$matches[$k] = $v;
}
}
适用于子字符串,不区分大小写
可在此处找到:您可以使用strtolower()
尽管其他答案使用regex和
preg.*
系列,但您可能最好使用preg.*
函数,因为它只用于查找字符串中是否有内容-stripos
更快
但是,stripos
不接受针阵列,因此我编写了一个函数来实现这一点:
function stripos_array($haystack, $needles){
foreach($needles as $needle) {
if(($res = stripos($haystack, $needle)) !== false) {
return $res;
}
}
return false;
}
如果找到匹配项,此函数返回偏移量,否则返回false。示例案例:
$foo = 'evil string';
$bar = 'good words';
$baz = 'caseBADcase';
$badwords = array('bad','evil');
var_dump(stripos_array($foo,$badwords));
var_dump(stripos_array($bar,$badwords));
var_dump(stripos_array($baz,$badwords));
# int(0)
# bool(false)
# int(4)
示例用法:
if(stripos_array($word, $evilwords) === false) {
echo "$word is fine.";
}
else {
echo "Bad word alert: $word";
}
通过使用不区分大小写的正则表达式过滤数组中的每个单词,您可以得到单词列表
<?php
$haystack = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
$needle = 'DAY';
$matches = array_filter($haystack, function($var){return (bool)preg_match("/$needle/i",$var);});
print_r($matches);
例如,使用
strpos
或阅读有关正则表达式和preg.*
函数的内容请详细说明您的答案。虽然这可能会回答问题,但习惯上至少会在您的答案中添加一些注释或解释,这样人们可能会真正学到一些东西,而不是复制/粘贴代码。谢谢您的建议,刚才详细说明了答案:)
<?php
$haystack = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
$needle = 'DAY';
$matches = array_filter($haystack, function($var){return (bool)preg_match("/$needle/i",$var);});
print_r($matches);
Array
(
[0] => sunday
[1] => monday
[2] => tuesday
[3] => wednesday
[4] => thursday
[5] => friday
[6] => saturday
)