Search code examples
phpregexstringpreg-replacepreg-replace-callback

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;
});

Solution

  • 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