PHP preg_grep() Function
Example
Get items from an array which begin with "p":
<?php
$input = [
"Red",
"Pink",
"Green",
"Blue",
"Purple"
];
$result = preg_grep("/^p/i", $input);
print_r($result);
?>
Try it Yourself »
Definition and Usage
The preg_grep()
function returns an array containing only elements from the input that
match the given pattern.
Syntax
preg_grep(pattern, input, flags)
Parameter Values
Parameter | Description |
---|---|
pattern | Required. Contains a regular expression indicating what to search for |
input | Required. An array of strings |
flags | Optional. There is only one flag for this function. Passing the
constant PREG_GREP_INVERT will make the function return
only items that do not match the pattern. |
Technical Details
Return Value: | Returns an array containing strings that matched the provided pattern |
---|---|
PHP Version: | 4+ |
❮ PHP RegExp Reference