Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically Replacing by a Function in PHP

Is there a way to dynamically replace by a function, similar to how .replace 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 preg_replace 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;
});
like image 573
Derek 朕會功夫 Avatar asked Oct 29 '22 17:10

Derek 朕會功夫


1 Answers

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

like image 92
Mohammad Avatar answered Nov 09 '22 08:11

Mohammad