开发者

Control replacements in regex

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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜