Using Preg_Grep Function to Search an Array in PHP

by Naveenkumar 2013-05-08 17:41:18

Hi,

The PHP function, preg_grep, is used to search an array for specific patterns and then return a new array based on that filtering.

There are two ways to return the results.

You can return them as is, or you can invert them (instead of only returning what matches, it would only return what does not match.)

syntax: preg_grep ( search_pattern, $your_array, optional_inverse )

*The search_pattern needs to be a regular expression.



$data = array(0, 1, 2, 'three', 4, 5, 'six', 7, 8, 'nine', 10);

$mod1 = preg_grep("/4|5|6/", $data); // return matching value

$mod2 = preg_grep("/[0-9]/", $data, PREG_GREP_INVERT); // return mismatching values

print_r($mod1);

print_r($mod2);



Output :

Array ( [4] => 4 [5] => 5 )
Array ( [3] => three [6] => six [9] => nine )


print_r($mod1)--> Here we are searching for anything that contains 4, 5, or 6. When our result is printed below we only get 4 and 5, because 6 was written as 'six' so it did not match our search.

print_r($mod2)--> which is searching for anything that contains a numeric character. Here we include PREG_GREP_INVERT. This will invert our data, so instead of outputting numbers, it outputs all of our entries that where not numeric (three, six and nine)

1247
like
0
dislike
0
mail
flag

You must LOGIN to add comments