Francis
Francis

Reputation: 254

How to preg_replace with incremental counted numbers using php?

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

Answers (1)

Rolando Isidoro
Rolando Isidoro

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

Related Questions