2

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

0

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

1

Use preg_replace_callback

$count = 0;
preg_replace_callback('/figno/', 'rep_count', $string);

function rep_count($matches) {
  global $count;
  return $count++;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.