开发者

Control replacements in regex

开发者 https://www.devze.com 2023-04-05 23:06 出处:网络
I have a string like test 开发者_运维百科[test id=\"123\" /] test [test id=\"234\" /] [test id=\"345\" /] test

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

精彩评论

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