Friday, 23 January 2015

Preg_Grep PHP Function

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.) It is phrased as: preg_grep ( search_pattern, $your_array, optional_inverse ) The search_pattern needs to be a regular expression. If you are unfamiliar with them this article gives you an overview of the syntax.
<?php
 $data = array(0, 1, 2, 'three', 4, 5, 'six', 7, 8, 'nine', 10,6); 
$mod1 = preg_grep("/4|5|6/", $data);
 $mod2 = preg_grep("/[0-9]/", $data, PREG_GREP_INVERT);
 print_r($mod1); 
echo "<br>";
 print_r($mod2); ?>
This code would result in the following data: 
Array ( [4] => 4 [5] => 5 [11]=>6) 
Array ( [3] => three [6] => six [9] => nine )
First we assign our $data variable. This is a list of numbers, some in alpha form, others in numeric. The first thing we run is called $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.
Next we run $mod2, which is searching for anything that contains a numeric character. But this time 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).

0 comments:

Post a Comment