PHP preg_grep() Function

PHP 正则表达式(PCRE)PHP Regular Expressions (PCRE)

The preg_grep function is used to return array entries that match the pattern.

Syntax

array preg_grep ( string $pattern , array $input [, int $flags = 0 ] )

Returns an array consisting of elements from the given array input that match the pattern pattern.

Parameter description:

  • $pattern: The pattern to search for, in string form.
  • $input: The input array.
  • $flags: If set to PREG_GREP_INVERT, this function returns an array consisting of elements from the input array that do not match the given pattern pattern.

Example

Returns elements matching the specified pattern from the array:

<?php $array = array(1, 2, 3.4, 53, 7.9); //Return all elements containing floating-point numbers $fl_array = preg_grep("/^(\d+)?\.\d+$/", $array); print_r($fl_array); ?>

The execution result is as follows:

Array
(
    [2] => 3.4
    [4] => 7.9
)

It can be seen that preg_grep only returns the floating-point numbers from the array.

PHP 正则表达式(PCRE)PHP Regular Expressions (PCRE)

Other Extensions