Learning
Learning

Reputation: 868

preg_replace() the same string by increment variable based on occurrences order

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_replacein the place of str_replace() too but same output

Upvotes: 2

Views: 445

Answers (2)

Rizier123
Rizier123

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

Aman Rawat
Aman Rawat

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

Related Questions