How to Use the PHP preg_grep() Function

09/05/2021

Contents

In this article, you will learn how to use the PHP preg_grep() function.

PHP preg_grep() Function

The preg_grep function in PHP is used to search an array for elements that match a specified pattern and return them in a new array.

Syntax:
preg_grep(pattern, input_array, flags)
Parameters:
  • pattern is a regular expression pattern used for matching the elements in the input_array.
  • input_array is the array to search through.
  • flags is an optional argument that can be used to modify the behavior of the function. The most commonly used flag is PREG_GREP_INVERT which returns elements that do not match the pattern.
Example:
<?php
  $fruits = array("apple", "banana", "cherry", "orange");
  $pattern = '/^[a,b]/';
  $result = preg_grep($pattern, $fruits);
  print_r($result);
?>
Output:

Array
(
    [0] => apple
    [1] => banana
)

In the example above, preg_grep is used to search through the array $fruits and find elements that start with either “a” or “b”. The regular expression pattern ‘/^[a,b]/’ specifies this requirement. The ^ symbol at the start of the pattern matches the start of a string, while the square brackets [a,b] match either “a” or “b”.

The resulting array contains only the elements from $fruits that match the pattern.

The preg_grep() function is commonly used in PHP to filter arrays based on complex conditions specified using regular expressions. By using the appropriate pattern, you can search for elements that contain specific substrings, match specific formats, or follow any other pattern you can specify using regular expressions.

It’s important to note that the preg_grep function performs a case-sensitive search, unless you specify otherwise using the i (case-insensitive) flag in your pattern.