Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1

(^150) CHAPTER 10 ■ SPL ITERATORS
Listing 10-8 demonstrates the use of the GET_MATCH operational mode.
Listing 10-8. Using the GET_MATCH $op_mode Parameter with RegexIterator
$arr = array('apple','avocado', 'orange', 'pineapple');
$arrIterator = new ArrayIterator($arr);
$iterator = new RegexIterator(
$arrIterator,
'/^(a\w{3})\w*$/',
RegexIterator::GET_MATCH
);
print_r(iterator_to_array($iterator));
Array
(
[0] => Array
(
[0] => apple
[1] => appl
)
[1] => Array
(
[0] => avocado
[1] => avoc
)
)
The regular expression used in Listing 10-8 is fairly simple. It matches an entire word-based
string starting with the letter a and consisting of three or more word characters. The pattern
within the parentheses, (a/w{3}), controls which part of the string is used by GET_MATCH—in
this case, the letter a and three word characters. The resulting array will contain the entire
matched string at position 0, followed by any captured subpatterns.
The next RegexIterator parameter, $spl_flags, allows you to tell the iterator whether you
want it to operate on the keys or on the values of the array. The default is to use values, however
you can use the class constant USE_KEY for this parameter to enable key operation.
Listing 10-9 demonstrates how to use RegexIterator to filter out entries from an array
where the array key is not numeric. The resulting array will have only numeric keys and their
associated values.
Listing 10-9. Using a RegexIterator to Extract Numeric Keys
$arr = array(0=>'A', 1=>'B', 2=>'C', 3=>'D', 'nonnumeric'=>'useless');
$arrIterator = new ArrayIterator($arr);
McArthur_819-9C10.fm Page 150 Friday, February 22, 2008 9:08 AM

Free download pdf