PHP | preg_grep() Function
Last Updated :
08 Jun, 2018
Improve
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 :
php
php
php
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.
<?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:
Program 2: Take an example of PREG_GREP_INVERT, which is invert data instead of output numbers to be non-numeric values in php.
Array ( [1] => for )
<?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:
Program 3: Example where no match found, then it return NULL array.
Array ( [1] => one [3] => two [4] => three [7] => Six [9] => Eight [10] => Nine )
<?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);
?>
Output:
References :http://php.net/manual/en/function.preg-grep.php
Array ( )