Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1
CHAPTER 10 ■ SPL ITERATORS^149

The filter in Listing 10-6 rejects any entries that are not greater than three. You could also
create a generic comparison filter by overriding the __construct() method and passing 3 as a
parameter. Just remember that you also need to call the base class’s constructor.

RegexIterator
The RegexIterator is an extended FilterIterator that allows you to use various regular
expression patterns for matching and modifying an iterator’s dataset.
The RegexIterator’s most basic use is to match string keys or values to a pattern and
return those keys that match. As an example, Listing 10-7 shows how to find all entries that
start with the letter a.

Listing 10-7. Using a Basic RegexIterator Iterator

$arr = array('apple','avocado', 'orange', 'pineapple');
$arrIterator = new ArrayIterator($arr);

$iterator = new RegexIterator($arrIterator, '/^a/');
print_r(iterator_to_array($iterator));

Array
(
[0] => apple
[1] => avocado
)

The RegexIterator offers much more than the simple matching demonstrated in Listing 10-7,
however. It has several other parameters that change the way that it works. The RegexIterator’s
constructor looks like this:

__construct ($iterator, $regex, $op_mode=0, $spl_flags=0, $preg_flags=0);

The first parameter of note is $op_mode, which controls the regular expression operation
mode. This parameter defaults to RegexIterator::MATCH, but can also be one of the following:

GET_MATCH: In this mode, the current key in the iterator is passed as the third parameter to
the preg_match() function. This will replace the current key with the &$matches data.

ALL_MATCHES: This option is the same as GET_MATCH but substitutes the function preg_match_
all for preg_match.

SPLIT: This mode uses the preg_split function and works identically to GET_MATCH and
ALL_MATCHES.

REPLACE: This option takes the current iterator value and performs a regular expression
replacement, overwriting the value with the replaced string.

McArthur_819-9C10.fm Page 149 Friday, February 22, 2008 9:08 AM

Free download pdf