PHP SPL RegexIterator从数组中删除不匹配的元素
问题描述:
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.
答
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));
答
You can try with preg_replace
sample code:
$re = "/^(value)(\\d+)/m";
$str = "LeaveThisInArray
value1
value2";
$subst = '$2:$1';
$result = preg_replace($re, $subst, $str);
Here is online demo
Try with ^(value)(\d*)
in your existing code.