206 of 410 menu

The preg_grep Function

The preg_grep function returns an array of elements that match a given regular expression. The first parameter of the function accepts a string with a regular expression, and the second - the array to search. The third optional parameter determines whether to return elements that do not match the regular expression.

Syntax

preg_grep(pattern, array, [flags]);

Flags

Flag Description
PREG_GREP_INVERT Inverts the result - returns elements that do NOT match the pattern.
PREG_GREP_NO_ERROR Does not generate an error for invalid regular expression (PHP 8.1+).

Example

Let's find all array elements that start with a digit:

<?php $arr = ['a1', '2b', 'c3', '4d', 'e5']; $res = preg_grep('/^\d/', $arr); var_dump($res); ?>

Code execution result:

['2b', '4d']

Example

Use the PREG_GREP_INVERT flag to get elements that do NOT match the regular expression:

<?php $arr = ['a1', '2b', 'c3', '4d', 'e5']; $res = preg_grep('/^\d/', $arr, PREG_GREP_INVERT); var_dump($res); ?>

Code execution result:

['a1', 'c3', 'e5']

Example

Find all array elements containing only digits:

<?php $arr = ['123', 'abc', '45', 'de', '678']; $res = preg_grep('/^\d+$/', $arr); var_dump($res); ?>

Code execution result:

['123', '45', '678']

See Also

  • the preg_match function,
    which performs a regular expression match check
  • the preg_replace function,
    which performs search and replace by regular expression
byenru