PHP in_array 正则表达式 haystack 数组
PHP in_array with regexp haystack array
PHP 函数 in_array
是否接受 REGEXP 数组作为第二个参数?
我在 PHP.net
上找不到任何相关信息
这是我目前使用的代码:
$haystack = [
"/^foo$/",
"/^bar$/",
"/^foobar$/"
];
function in_reg_array($needle, $haystack) {
foreach ($haystack as $straw)
if (preg_match($straw, $needle))
return TRUE;
return FALSE;
}
如果有人有更好的解决方案,我愿意接受建议。
编辑:
我不能将单个正则表达式与 foo|bar|foobar
一起使用,因为大海捞针各不相同。
preg_filter()
获取一组模式,替换它们,然后 returns 替换字符串。所以,如果它 returns 什么都没有,那么你就知道没有匹配项。
function in_reg_array($needle, $haystack) {
return preg_filter($haystack, '', $needle) !== null;
}
另一个选项:
$haystack = [
"^foo$",
"^bar$",
"^foobar$"
];
$string = ['foo', 'bar','baz', 'foo2'];
$result = preg_grep("/(".implode('|',$haystack).")/", $string);
输出:
array(2) {
[0]=> string(3) "foo"
[1]=> string(3) "bar"
}
PHP 函数 in_array
是否接受 REGEXP 数组作为第二个参数?
我在 PHP.net
这是我目前使用的代码:
$haystack = [
"/^foo$/",
"/^bar$/",
"/^foobar$/"
];
function in_reg_array($needle, $haystack) {
foreach ($haystack as $straw)
if (preg_match($straw, $needle))
return TRUE;
return FALSE;
}
如果有人有更好的解决方案,我愿意接受建议。
编辑:
我不能将单个正则表达式与 foo|bar|foobar
一起使用,因为大海捞针各不相同。
preg_filter()
获取一组模式,替换它们,然后 returns 替换字符串。所以,如果它 returns 什么都没有,那么你就知道没有匹配项。
function in_reg_array($needle, $haystack) {
return preg_filter($haystack, '', $needle) !== null;
}
另一个选项:
$haystack = [
"^foo$",
"^bar$",
"^foobar$"
];
$string = ['foo', 'bar','baz', 'foo2'];
$result = preg_grep("/(".implode('|',$haystack).")/", $string);
输出:
array(2) {
[0]=> string(3) "foo"
[1]=> string(3) "bar"
}