Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to work with RegexIterator::REPLACE mode?

Tags:

php

spl

What is wrong in my code:

$i = new RegexIterator(
  new ArrayIterator(array(
    'test1'=>'test888', 
    'test2'=>'what?', 
    'test3'=>'test999')),
  '/^test(.*)/',
  RegexIterator::REPLACE);

foreach ($i as $name=>$value)
  echo $name . '=>' . $value . "\n";

The iterator is empty, why? Thanks for your help!

like image 633
yegor256 Avatar asked Nov 14 '22 13:11

yegor256


1 Answers

If you ommit the operation mode (3rd parameter in your new RegexIterator statement) you'll get the matching values, like so:

$array = array('test1' => 'test888', 'test2' => 'what?', 'test3' => 'test999');
$pattern = '/^test(.*)/';

echo '<pre>';
echo "DEFAULT\n";
$arrayIterator = new ArrayIterator($array);
$regexIterator = new RegexIterator($arrayIterator, $pattern);
foreach ($regexIterator as $value) {echo "$value\n";}
echo '</pre>';

You can play with the different operation modes, depending on what you want. Go read up on the setMode documentation: http://www.php.net/manual/en/regexiterator.setmode.php

like image 65
Kris Lamote Avatar answered Dec 10 '22 23:12

Kris Lamote