English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

PHP Basic Tutorial

PHP Advanced Tutorial

PHP & MySQL

PHP Reference Manual

PHP preg_grep() Function Usage and Example

PHP Regular Expression (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 of elements that match the pattern in the given array input.

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 of elements in the input array that do not match the given pattern.

Online Examples

<?php
$array = array(1, 2, 3.4, 53, 7.9);
// Returns 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 in the array.

PHP Regular Expression (PCRE)