PHP Reference ยท Regular Expressions
PHP preg_grep() function
Reference for PHP preg_grep(): filter an array by a regular expression, keep or invert matches with PREG_GREP_INVERT, how keys are preserved and what it ignores.
The preg_grep() function walks over an array and returns the elements whose values match a regular expression. The name comes from the Unix grep tool. It is a quick way to filter a list of strings (file names, form inputs, log lines) without writing a loop.
The result keeps the original keys, so a filtered list is usually no longer a list with keys 0, 1, 2.... Wrap it in array_values() when you need a fresh numbering.
<?php print_r(preg_grep('/^\d+$/', ['10', 'x', '7']));
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
preg_grep( string $pattern, array $array, int $flags = 0 ): array|false
| Name | Description |
|---|---|
$pattern |
The regular expression, with delimiters and modifiers. |
$array |
The array whose values are tested. Keys are not tested. |
$flags |
0, or PREG_GREP_INVERT to return the elements that do not match. |
Return value: an array of the matching elements with their original keys, or false if the pattern is invalid or the engine fails.
Errors / Exceptions: an invalid pattern emits a warning and returns false. See preg_last_error().
Usage notes
- Only values are tested. To filter by key, pass
array_keys($array)and use the matches to select entries, as in the example above. - Non-string values are converted to strings first (
truebecomes"1",nullbecomes""). Arrays inside the array cause a warning and conversion to"Array". - The original array is not changed.
- No captures.
preg_grep()cannot give you matched groups. For that, loop withpreg_match(), or usearray_filter()with a callback. array_filter()is more flexible when the test is more than a pattern;preg_grep()is shorter when it is exactly a pattern.- Empty result is an empty array, which is falsy but is not an error. Compare with
falseto detect failures. - Use
/ufor UTF-8 values. A value that is invalid UTF-8 makes the whole call fail. - Anchors matter. Without
^and$, any value that contains the pattern anywhere matches.