PHP preg_replace foreach 循环中不起作用


php preg_replace not working within foreach loop

我有以下结构:

<?php
  $i = 0;
  foreach ($users as $user) {
    $i++;
    $string = '<span>The number is $i</span>';
    $string = preg_replace('/'<span.*?'/>$/e','',$string);
    echo $string;
  }
?>

它将$string附加到循环迭代的次数foreach而我只希望它在循环结束时显示为The number is 4一次。 如果在循环之外,preg_replace工作。如何echo一次输出并删除其余部分。我需要在循环内而不是在循环外进行。

这将做到这一点:

$i = 0;
foreach ($users as $user) {
   $i++;
   if ($i == count($users)) {
      $string = '<span>The number is $i</span>';
      $string = preg_replace('/'<span.*?'/>$/e','',$string);
      echo $string;
   }
}

但是,您可能需要考虑实现此目的的其他选项。您可以维护$i变量并在循环后立即输出它,因为这正是这样做的。

或者,你可以echo "<span>The number is ".count($users)."</span>";.在我的回答中,我假设你完全无法改变这件事,你的问题比这个简单的preg_replace更复杂。如果不是,请考虑简化操作。

我认为您需要的解决方案是输出缓冲:

// Start the output buffer to catch the output from the loop
ob_start();
$i = 0;
foreach ($users as $user) {
  $i++;
  // Do stuff
}
// Stop the output buffer and get the loop output as a string
$loopOutput = ob_get_clean();
// Output everything in the correct order
echo '<span>The number is '.$i.'</span>'.$loopOutput;