Derek 朕會功夫 Derek 朕會功夫 - 11 months ago 41
PHP Question

Dynamically Replacing by a Function in PHP

Is there a way to dynamically replace by a function, similar to how

works in JavaScript? A comparable use case would be I have a string with numbers and I would like to pass the numbers through a function:

"1 2 3" => "2 4 6" (x2)

The current
function doesn't seem to support a function for the argument.

For reference, in JavaScript it can be implemented as the following:

var str = "1 2 3";
str.replace(/\d+/g, function(num){
return +num * 2;

Answer Source

You should use preg_replace_callback() that has callback for regex matches. You can multiply matches digit in callback function.

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

Check result in demo