我有一些字符串的数组,我想用RegexIterator
替换匹配字符串上的一些东西,但也要在数组中保留不匹配的字符串。
这是我的代码:
$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));
我得到这个作为输出:
Array
(
[0] => 1:value
[1] => 2:value
)
但我想要的是:
Array
(
[0] => LeaveThisInArray
[1] => 1:value
[2] => 2:value
)
是否有我可以设置的任何标志或其他东西,因为我在 spl 文档中找不到太多。
你可以试试preg_replace
示例代码:
$re = "/^(value)(''d+)/m";
$str = "LeaveThisInArray'nvalue1'nvalue2";
$subst = '$2:$1';
$result = preg_replace($re, $subst, $str);
这是在线演示
尝试在现有代码中使用^(value)('d*)
。
我现在能想到的最接近的是这样的:
$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));