PHP Function Reference

PHP preg_grep() Function



The PHP preg_grep() function returns the array consisting of the elements of the specified array that match the given pattern.

Syntax

preg_grep(pattern, array, flags)

Parameters

pattern Required. Specify the pattern to search for, as a string.
array Required. Specify the input array.
flags Required. There is only one flag for this function. If set to PREG_GREP_INVERT, this function returns the elements of the input array that do not match the given pattern.

Return Value

Returns an array indexed using the keys from the input array, or false on failure.

Example:

The example below shows the usage of preg_grep() function.

<?php
$arr = array("Red",
             "Pink", 
             "Green", 
             "Blue", 
             "Purple");

//return all array elements 
//starting with letter P
$result = preg_grep("/^p/i", $arr);
print_r($result);
?>

The output of the above code will be:

Array
(
    [1] => Pink
    [4] => Purple
)

Example:

Consider the example below where the flag parameter is used to select all elements of the array which do not match with specified pattern.

<?php
$arr = array("Red",
             "Pink", 
             "Green", 
             "Blue", 
             "Purple");

//return all array elements 
//not starting with letter P
$result = preg_grep("/^p/i", $arr, 
                    PREG_GREP_INVERT);
print_r($result);
?>

The output of the above code will be:

Array
(
    [0] => Red
    [2] => Green
    [3] => Blue
)

Example:

Consider one more example where this function is used to select all array elements containing floating point numbers.

<?php
$arr = array("10.5",
             "Hello", 
             100.25, 
             10, 
             1e5,
             "abc.com");

//return all array elements containing 
//floating point numbers
$result = preg_grep("/^(\d+)?\.\d+$/", $arr);
print_r($result);
?>

The output of the above code will be:

Array
(
    [0] => 10.5
    [2] => 100.25
)

❮ PHP RegEx Reference