有可能使用通配符
array_search吗?
不,但您可以使用正则表达式(支持通配符)和preg_grep函数.
例:
$array = explode(',', "House,Car,Boat,Horse,Pool Boy");
# remove all strings from array that do not contain "ho"
$array = preg_grep('~ho~i', $array, PREG_GREP_INVERT);
Run Code Online (Sandbox Code Playgroud)
那么数组是:
Array
(
[1] => Car
[2] => Boat
[4] => Pool Boy
)
Run Code Online (Sandbox Code Playgroud)
由于编写正则表达式模式可能很复杂,因此使用辅助函数将SQL LIKE模式转换为正则表达式可能会很方便,因此可以更容易地使用它:
$array = explode(',', "House,Car,Boat,Horse,Pool Boy");
# Search for "Ho" at the beginning of each string
$regex = like_to_regex('Ho%');
$array = preg_grep($regex, $array, PREG_GREP_INVERT);
print_r($array);
/**
* convert a MySQL LIKE pattern into a pcre pattern
*/
function like_to_regex($like, $casesensitive = FALSE, $escapechar = '\\')
{
$pattern = sprintf('~(?<!%1$s)(%1$s{2}|%%|_)~', preg_quote($escapechar));
$tokens = preg_split($pattern, $like, 0, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
foreach($tokens as &$token)
{
switch($token)
{
case $escapechar.$escapechar:
$token = preg_quote($escapechar);
break;
case '_':
$token = '.';
break;
case '%':
$token = '.*';
break;
default:
$token = preg_quote($token);
}
}
return sprintf('~^%s$~%s', implode('', $tokens), $casesensitive ? '':'i');
}
Run Code Online (Sandbox Code Playgroud)