开发者

how to work with RegexIterator::REPLACE mode?

开发者 https://www.devze.com 2022-12-15 05:38 出处:网络
What is wrong in my code: $i = new RegexIterator( new ArrayIterator(array( \'test1\'=>\'test888\', \'test2\'=>\'what?\',

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开发者_如何学JAVA help!


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


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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号