Jarmark Jarmark - 3 months ago 9
PHP Question

Not incrementing variable in an anonymous callback function

I've tried to use both

preg_replace
and
preg_replace_callback
maybe in a wrong way. What I do wrong?

$str = '/admin/companies/{company}/projects/{project}/photos/{photo}/delete';
$pattern = '/({\w+})/';
$replacement = ['str_1', 'str_2', 'str_3'];

$i = 0;

$result = preg_replace_callback($pattern, function($matches) use ($i, $replacement) {
return $replacement[$i++];
}, $str);



  • Current Output:    
    /admin/companies/str_1/projects/str_1/photos/str_1/delete

  • Expected Output:
    /admin/companies/str_1/projects/str_2/photos/str_3/delete


Answer

You want to pass $i by reference, so it gets updated when you increment it with $i++:

$result = preg_replace_callback($pattern, function($matches) use (&$i, $replacement) {
    return $replacement[$i++];
}, $str);

Notice the & before $i.