Reputation: 868
My string:
$string = "figno some text and another figno then last figno";
Expected output
1 some text and another 2 then last 3
I tried so far:
preg_match_all("/figno/s",$string,$figmatch);
$figno=0;
for($i=0;$i<count($figmatch[0]);$i++){
$figno=$figno+1;
$string=str_replace($figmatch[0][$i],$figno,$string);
}
But it replaces all the occurrences at a time. I tried preg_replace
in the place of str_replace()
too but same output
Upvotes: 2
Views: 445
Reputation: 59701
Just use preg_replace_callback()
, so that it calls the anonymous function for every match which you get and then pass the variable $count
by reference to keep track of the amount of matches, e.g.
<?php
$string = "figno some text and another figno then last figno";
$count = 1;
echo preg_replace_callback("/figno/s", function($m)use(&$count){
return $count++;
}, $string);
?>
output:
1 some text and another 2 then last 3
Upvotes: 1
Reputation: 2625
Use preg_replace_callback
$count = 0;
preg_replace_callback('/figno/', 'rep_count', $string);
function rep_count($matches) {
global $count;
return $count++;
}
Upvotes: 1