In this article, you will learn about the preg_grep function in PHP. The preg_grep() function in PHP returns an array containing only elements from the input that matches the given pattern.
what is the syntax of the PREG_GREP function in php?
preg_grep(pattern, input, flags)
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. |
examples of the PREG_GREP function
Example 1. In this example, we 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);
?>