I am trying to loop through every [footnote]
and replace it with some HTML. Here is some sample text:
Hello [footnote], how are you [footnote], what are you up to [footnote]?
And using preg_match_all to create a count:
$match_count = preg_match_all("/\[footnote]/", $content);
I then use this count as a loop, to find and replace the text with appropriate HTML:
for ($i=0; $i < $match_count; $i++) {
$new_content = str_replace('[footnote]', "<span class='footnote'>$i</span>", $content);
}
However, after, when I echo $new_content;
each [footnote]
has the same number, 2:
<span class="footnote">2</span>
<span class="footnote">2</span>
<span class="footnote">2</span>
Would anyone know why this number is not incrementing? This is what I want
<span class="footnote">1</span>
<span class="footnote">2</span>
<span class="footnote">3</span>
str_replace
replaces everything at once, you need preg_replace
which supports $limit
(=number of replacements to make):
$content = "Hello [footnote], how are you [footnote], what are you up to [footnote]?";
$i = 0;
do {
$i++;
$content = preg_replace('~\[footnote\]~', "<span>$i</span>", $content, 1, $count);
} while($count);
print $content;
Note that the 5th parameter, $count
makes your counting code superfluous - we just keep replacing until no more replacement could be made.
Since you are trying to replace a literal string, you can avoid to use a regex. Example:
$str = 'Hello [footnote], how are you [footnote], what are you up to [footnote]?';
$arr = explode('[footnote]', $str);
$count = 1;
$result = array_reduce($arr, function ($carry, $item) use (&$count) {
return (isset($carry))
? $carry . '<span class="footnote">' . $count++ . '</span>' . $item
: $item;
});
print_r($result);
you can do like this
$i = 0;
preg_replace_callback('/[footnote]/', 'replaces_counter', $content);
function replaces_counter($matches) {
global $i;
return "<span class='footnote'>".$i++."</span>";
}