数组搜索中的通配符

时间:2011-10-19 08:48:49

标签: php arrays search wildcard

可以在array_search中使用通配符吗?我想搜索字符串的一部分然后

类似(带星号)

print $pos = array_search('abitofastring%', $vars['myarray']);
unset($vars['myarray'][$pos]);

1 个答案:

答案 0 :(得分:6)

  

是否可以使用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);

然后数组是:

Array
(
    [1] => Car
    [2] => Boat
    [4] => Pool Boy
)

由于编写正则表达式模式可能很复杂,因此有一个帮助函数可以将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');
}