Filter PHP Array with Regex Using preg_grep
This article explains how to use the built-in
preg_grep() function in PHP to filter array elements using
regular expressions. You will learn the syntax of the function, explore
practical code examples for matching and excluding patterns, and
understand how to handle array keys during the filtering process.
What is preg_grep()?
The preg_grep() function is a built-in PHP function used
to search an array for elements that match a specific regular
expression. It returns a new array containing only the elements that
match (or do not match, depending on your settings) the given
pattern.
Syntax
preg_grep(string $pattern, array $array, int $flags = 0): array$pattern: The regular expression pattern to search for, as a string.$array: The input array containing the strings you want to filter.$flags: Optional. If set toPREG_GREP_INVERT, the function returns array elements that do not match the pattern.
Practical Examples
1. Basic Matching (Finding Matches)
By default, preg_grep() returns all elements that match
the regular expression. In this example, we will filter an array to find
elements that start with the letters “ap”.
<?php
$input = ["apple", "banana", "apricot", "cherry", "grape"];
// Regex to match words starting with "ap"
$pattern = "/^ap/";
$result = preg_grep($pattern, $input);
print_r($result);
?>Output:
Array
(
[0] => apple
[2] => apricot
)
2. Inverted Matching (Excluding Matches)
If you want to filter out elements that match a pattern, use the
PREG_GREP_INVERT flag. This returns all elements that
do not match the regular expression.
<?php
$input = ["apple", "banana", "apricot", "cherry", "grape"];
// Regex to match words starting with "ap"
$pattern = "/^ap/";
// Invert the match to exclude words starting with "ap"
$result = preg_grep($pattern, $input, PREG_GREP_INVERT);
print_r($result);
?>Output:
Array
(
[1] => banana
[3] => cherry
[4] => grape
)
Handling Array Keys
As shown in the outputs above, preg_grep() preserves the
original keys of the input array. If you need to reset the array keys
numerically (starting from 0), pass the result through the
array_values() function.
<?php
$input = ["apple", "banana", "apricot", "cherry"];
$pattern = "/^ap/";
$filtered = preg_grep($pattern, $input);
// Reset keys
$reindexed = array_values($filtered);
print_r($reindexed);
?>Output:
Array
(
[0] => apple
[1] => apricot
)