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:
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.
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.
References :https://www.php.net/manual/en/function.preg-grep.php