通过PHP中的函数动态替换

Der*_*會功夫 5 php regex string preg-replace preg-replace-callback

有没有办法通过函数动态替换,类似于.replaceJavaScript中的工作方式?一个类似的用例是我有一个带数字的字符串,我想通过一个函数传递数字:

"1 2 3" => "2 4 6"  (x2)
Run Code Online (Sandbox Code Playgroud)

当前preg_replace函数似乎不支持参数的函数.

作为参考,在JavaScript中它可以实现如下:

var str = "1 2 3";
str.replace(/\d+/g, function(num){
    return +num * 2;
});
Run Code Online (Sandbox Code Playgroud)

Moh*_*mad 2

您应该使用preg_replace_callback()它来进行正则表达式匹配的回调。您可以在回调函数中乘以匹配数字。

$newStr = preg_replace_callback("/\d+/", function($matches){
    return $matches[0] * 2;
}, $str); 
Run Code Online (Sandbox Code Playgroud)

在演示中检查结果