preg_grep

Return array entries that match the pattern

Syntax

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

Parameters

pattern

The pattern to search for, as a string.

array

The input array.

flags

If set to PREG_GREP_INVERT, this function returns the elements of the input array that do not match the given pattern.

Return

Returns an array indexed using the keys from the array array, or false on failure.

Examples

1 · pattern array

<?

$pattern = "#^(\d+)?\.\d+$#";
$array = array(0, 1.1, 22.22, 333.333, 4);

$return = preg_grep($pattern, $array);

print_r($return);

?>
Array
(
    [1] => 1.1
    [2] => 22.22
    [3] => 333.333
)

2 · flags

<?

$pattern = "#^(\d+)?\.\d+$#";
$array = array(0, 1.1, 22.22, 333.333, 4);
$flags = PREG_GREP_INVERT;

$return = preg_grep($pattern, $array, $flags);

print_r($return);

?>
Array
(
    [0] => 0
    [4] => 4
)

preg_filter

preg_last_error

preg_match

preg_match_all

preg_quote

preg_replace

preg_replace_callback

preg_replace_callback_array

preg_split

PHP

Home Menu