I have the following structure :
<?php
$i = 0;
foreach ($users as $user) {
$i++;
$string = '<span>The number is $i</span>';
$string = preg_replace('/\<span.*?\/>$/e','',$string);
echo $string;
}
?>
It appends the $string the number of times foreach loop iterate whereas i just want it to display one time as The number is 4 at the end of the loop. preg_replace works if outside of the loop. How can i echo the output one time and delete rest. I need to do it within the loop and not outside it.
This will do it:
Though, you might want to consider other options for achieving this. You may maintain your
$ivariable and output it right after the loop, as this is what this does exactly.Or, you could just
echo "<span>The number is ".count($users)."</span>";.In my answer, I assumed you totally can’t change this things, and that your problem is more complicated than this simple
preg_replace. If it’s not, consider simplifying things.