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;
});
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With