Dynamic function replacement in PHP

Is there a way to dynamically replace with a function similar to how .replace works in JavaScript? Comparable use case: I have a string with numbers, and I would like to pass numbers through a function:

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

The current preg_replace function does not seem to support the function for the argument.

For reference, in JavaScript it can be implemented as follows:

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

You should use preg_replace_callback() , which has a callback for regular expression matches. You can multiply match numbers in the callback function.

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

Check the result in the demo

+2
source

Source: https://habr.com/ru/post/1259359/


All Articles