5

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;
});
Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247

1 Answers1

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

Mohammad
  • 21,175
  • 15
  • 55
  • 84
  • Is there a way to get the index as well? – Derek 朕會功夫 Nov 06 '16 at 09:12
  • @Derek朕會功夫 The function return matches part in array `$matches` and you can see all index of it using `print_r($matches)` – Mohammad Nov 06 '16 at 09:13
  • @Derek朕會功夫 Yes, your code has two problem. First, you should set regex parameter of function between `//`. Second, you should increase value of `$i` before `return` because return break the function execution. See https://3v4l.org/2bYAh – Mohammad Nov 06 '16 at 09:30
  • Yea I realized the problems after a while... I think I really need a coffee right now. Anyway, thanks for the answer. – Derek 朕會功夫 Nov 06 '16 at 09:34