PHP | preg_grep() Function
Last Updated :
11 Jul, 2025
The
preg_grep() is an inbuilt function in PHP. It returns the array consisting of the elements of the input array that match with the given pattern.
Syntax :
array preg_grep ( $pattern, $input [, $flags] )
Parameters Used:
The
preg_grep() function take three parameters that are described below:
- $pattern: The $pattern is an string element which is searched in string array.
- $input: The $input is the original string array.
- $flags: The $flags is used for signalize and its variable type used for indicates two states True or False to control the program. If the flag is set to PREG_GREP_INVERT, the function returns elements of the input array that do not match to the given pattern.
Return Values: The function returns array indexed using the keys from the input array.
Program 1:
php
<?php
// PHP program to implement
// preg_grep() function
// original array elements
$inputstrVal =array("Geeks", "for", "Geeks", '2018' );
// Search elements "o", followed by one
// or more letters.
$result=preg_grep ('/o(\w+)/', $inputstrVal );
print_r($result);
?>
Output:
Array
(
[1] => for
)
Program 2: Take an example of
PREG_GREP_INVERT, which is invert data instead of output numbers to be non-numeric values in php.
php
<?php
// PHP program to implement preg_grep()
// function input string
$inputstrVal= array(1, "one", 2, "two",
"three", 4, 5, "Six", 7,
"Eight", "Nine", 10,
11, 12, 13);
// Used preg_grep with PREG_GREP_INVERT
$result = preg_grep("/[0-9]/", $inputstrVal,
PREG_GREP_INVERT);
// Print result
print_r($result);
?>
Output:
Array
(
[1] => one
[3] => two
[4] => three
[7] => Six
[9] => Eight
[10] => Nine
)
Program 3: Example where no match found, then it return
NULL array.
php
<?php
// PHP program to implement
// preg_grep() function
//original array elements
$inputstrVal =array(0 =>"Geeks",
1 =>"for",
2 => "Geeks",
3 => '2018',
);
// Search elements "x", followed by one
// or more letters.
$result=preg_grep ('/x(\w+)/', $inputstrVal );
print_r($result);
?>
References :https://www.php.net/manual/en/function.preg-grep.php