Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

RegexIterator

Select iterated values with a PCRE pattern.

Version: PHP 8.4; repository runtime, production runtime not attested

Syntax

new RegexIterator($iterator, $pattern, RegexIterator::GET_MATCH)

Select iterated values with a PCRE pattern. MATCH keeps matching originals, while GET_MATCH emits match arrays including captures. MATCH and GET_MATCH preserve keys. USE_KEY selects matching against keys instead of values. In REPLACE mode with USE_KEY the replacement changes the key and retains its value. Choose mode based on whether the consumer expects original data or match details.

$it=new RegexIterator(new ArrayIterator(["a"=>"id-12","b"=>"none"]),"~^id-(\\d+)$~",RegexIterator::GET_MATCH);
echo json_encode(iterator_to_array($it));
$rename=new RegexIterator(new ArrayIterator(["id-11"=>"kept"]),"~[0-9]+~",RegexIterator::REPLACE,RegexIterator::USE_KEY); $rename->replacement="xx"; echo PHP_EOL,json_encode(iterator_to_array($rename));
{"a":["id-12","12"]}
{"id-xx":"kept"}

Examples

<?php
$it=new RegexIterator(new ArrayIterator(["a"=>"id-12","b"=>"none"]),"~^id-(\\d+)$~",RegexIterator::GET_MATCH);
echo json_encode(iterator_to_array($it));
$rename=new RegexIterator(new ArrayIterator(["id-11"=>"kept"]),"~[0-9]+~",RegexIterator::REPLACE,RegexIterator::USE_KEY); $rename->replacement="xx"; echo PHP_EOL,json_encode(iterator_to_array($rename));

Result

{"a":["id-12","12"]}
{"id-xx":"kept"}

Sources