Reputation: 254
I need to replace a certain pattern with incremental counted numbers. My code:
$text = "Hello (apple) hello (banana) hello (cucumber)";
$pattern = '/\(([^\)]*)\)/s';
$i = 0;
$returnText = preg_replace_callback($pattern, function($matches) use ($i) {
return '<sup>['.$i++.']</sup>';
}, $text);
echo $returnText;
The result:
Hello [0] hello [0] hello [0]
What i need:
Hello [0] hello [1] hello [2]
What am i doing wrong?
Upvotes: 1
Views: 855
Reputation: 5114
You forgot to pass $i by reference. Just add the & before $i:
$returnText = preg_replace_callback($pattern, function($matches) use (&$i)
Upvotes: 4