PHP | preg_grep() Function
Last Updated :
08 Jun, 2018
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
$inputstrVal = array ( "Geeks" , "for" , "Geeks" , '2018' );
$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
$inputstrVal = array (1, "one" , 2, "two" ,
"three" , 4, 5, "Six" , 7,
"Eight" , "Nine" , 10,
11, 12, 13);
$result = preg_grep( "/[0-9]/" , $inputstrVal ,
PREG_GREP_INVERT);
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
$inputstrVal = array (0 => "Geeks" ,
1 => "for" ,
2 => "Geeks" ,
3 => '2018' ,
);
$result =preg_grep ( '/x(\w+)/' , $inputstrVal );
print_r( $result );
?>
|
References :http://php.net/manual/en/function.preg-grep.php
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...