XML technologies / Regular expressions / PHP / The preg functions / preg_grep

(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)

preg_grep(pattern, input [, flags ])

Parameters

pattern

The pattern parameter: a regex with delimiters and optional modifiers.

input

An array whose values are copied to the returned array if they match pattern .

flags

The optional flag PREG_GREP_INVERT.

Return value

An array containing values from input that match regex pattern (or, with option PREG_GREP_INVERT, that do not match the regex).

Explanation

Using preg_grep selects values from an array and creates a new array containing only values matching the regex (or, with PREG_GREP_INVERT, those not matching it). The original array remains unchanged.

The following simple example

preg_grep('/\s/', $input);

filters $input to retain elements containing whitespace. The inverse is:

preg_grep('/\s/', $input, PREG_GREP_INVERT);

This selects elements containing no whitespace. Note that this differs from:

preg_grep('/^\S+$/', $input);

Here, array elements with empty values of length zero are not copied.

  

 

 

 

German edition copyright © 2008 by O’Reilly Verlag GmbH & Co. KG
You may print the online version for private use.
Otherwise, this chapter from "Reguläre Ausdrücke" is subject to the same terms as the bound edition: the work and all its parts are protected by copyright. All rights reserved, including reproduction, translation, microfilming, storage and processing in electronic systems.

O’Reilly Verlag GmbH & Co. KG, Balthasarstr. 81, 50670 Köln

back to top