preg_grep
Returns the array elements that match a pattern.
Syntax
preg_grep(string $pattern, array $array, int $flags = 0): array|falseParameters
| Parameter | Type | Description |
|---|---|---|
| $pattern | string | The regular expression. |
| $array | array | An array of strings. |
| $flags | int | Optional. `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.pngNotes
Keys are preserved. For a list without gaps wrap the result in array_values().
See also
- preg_match — Tests a string against a regular expression.
- array_filter — Keeps the array elements that pass a test.
- preg_match_all — Finds every match of a regular expression.
In the tutorial
- Regular expressions — Regular expressions in PHP — preg_match, preg_replace, preg_split, groups and the basic pattern notation.