I have a string like
test 开发者_运维百科[test id="123" /] test [test id="234" /] [test id="345" /] test
How can I replace each [test ... /]
with something else, but control each replacement (by index) ?
I may want first match to be replaced with something, but the 2nd one with something else
Sounds like you want preg_replace_callback()
.
$index = 0;
preg_replace_callback('/\[test\sid="(?P<id>.+?)"\s*\/\]/', function() use (&$index) {
var_dump($index, func_get_args());
$index++;
}, $str);
CodePad.
You can access $index
to determine what iteration of the replacement you are on.
精彩评论