Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

preg_grep

Returns the array elements that match a pattern.

Syntax

preg_grep(string $pattern, array $array, int $flags = 0): array|false

Parameters

ParameterTypeDescription
$patternstringThe regular expression.
$arrayarrayAn array of strings.
$flagsintOptional. `PREG_GREP_INVERT` returns the non-matching ones.

Return value

array|falseAn array of the matching elements with the original keys.

Examples

Images only:

<?php
 
$files = ['photo.jpg', 'notes.txt', 'logo.png'];
 
echo implode(', ', preg_grep('/\.(jpg|png)$/', $files));

Output:

photo.jpg, logo.png

Notes

Keys are preserved. For a list without gaps wrap the result in array_values().

See also

In the tutorial

  • Regular expressions — Regular expressions in PHP — preg_match, preg_replace, preg_split, groups and the basic pattern notation.

Thanks for reading!

Donate to the site — we work hard for you.