Php Search_Array using Wildcard

2020-01-29 08:33发布

问题:

i m trying to search an array which contains patterns like

mike_45
peter_23
jim_12

and wants to search the particular pattern someway like

array_search('mike*',$array);

can somebody pls suggest me a useful way to do this

thanks in advance...

回答1:

Just use preg_grep here:

preg_grep("/^mike.*/", $array);


回答2:

With array_search() I dont see, that this is possible. I would array_filter() give a try. Also look at fnmatch(). Untested:

$pattern = 'mike*';
$array = array('mike_45','peter_23','jim_12');
$array = array_filter($array, function($entry) use ($pattern) {
  return fnmatch($pattern, $entry);
});

Requires PHP5.3 and also see my comment on hsz's answer. Except that this one dont need to rewrite the search pattern, its similar.



回答3:

Another way to wildcard search is to turn the array back into a string variable and then use strpos function. This will provide a true/false logical on if the string can match any array entry.

strpos(implode($array), 'mike');

This can be used in the following way.

if(strpos(implode($array), "mike"))
Perform actions here