how to work with RegexIterator::REPLACE mode?

若如初见. 提交于 2019-12-23 10:22:21

问题


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!


回答1:


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




回答2:


As said already, it's a bug in PHP. I reported it to php.net: http://bugs.php.net/bug.php?id=50579




回答3:


Consider the following code

$mixedArray=array(
    'tester2',
    'tes1',
    'bad4',
    '2good2',
    '2birds',
    'birds8',
    '8young girls',
    '6 young boys'
);


$ait=new ArrayIterator($mixedArray);
$regexIt=new RegexIterator($ait,'/^(\d+)(\w+)/', RegexIterator::REPLACE);
$regexIt->replacement='$2:$1';

foreach($regexIt as $key=>$value){
    echo $value."<br>";
}

Output

good2:2
birds:2
young:8 girls


来源:https://stackoverflow.com/questions/1957069/how-to-work-with-regexiteratorreplace-mode

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!