Search code examples
phpregexspl

PHP SPL RegexIterator removes unmatched elements from array


I have array with some strings and i want to use RegexIterator to replace some stuff on matched string but to also leave un-matched strings in array.

Here is my code:

    $a = new ArrayIterator(array('LeaveThisInArray','value1', 'value2')); 
    $i = new RegexIterator($a, '/^(value)(\d+)/', RegexIterator::REPLACE); 
    $i->replacement = '$2:$1'; 

    print_r(iterator_to_array($i)); 

And i get this as output:

    Array
(
    [0] => 1:value
    [1] => 2:value
)

But what i wanted is this:

 Array
        (
            [0] => LeaveThisInArray
            [1] => 1:value
            [2] => 2:value
        )

Is there any flag i can set or something, because i cant find much in the spl documentation.


Solution

  • The closest I can think about for this right now is like this:

    $a = new ArrayIterator(array('LeaveThisInArray','value1', 'value2')); 
    $i = new RegexIterator($a, '/^(?:(value)(\d+))?/', RegexIterator::REPLACE); 
    $i->replacement = '$2$1'; 
    
    print_r(iterator_to_array($i));