php preg_replace在foreach循环中不工作

php preg_replace在foreach循环中不工作,php,foreach,preg-replace,Php,Foreach,Preg Replace,我的结构如下: <?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而

我的结构如下:

<?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
而我只希望它显示一次
循环结束时的次数是4<代码>预替换
在循环外工作。我怎样才能
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=0;
foreach($users作为$user){
$i++;
如果($i==计数($users)){
$string='数字是$i';
$string=preg\u replace('/\$/e',''$string);
echo$字符串;
}
}

但是,您可能需要考虑其他选项来实现这一点。您可以维护

$i
变量,并在循环后立即输出它,因为这正是它所做的

或者,您可以只
回显“数字是”.count($users)”
在我的回答中,我假设你完全不能改变这些事情,你的问题比这个简单的
preg\u replace
更复杂。如果不是,考虑简化事物。

< P>我认为你需要的解决方案是:

//启动输出缓冲区以捕获循环的输出
ob_start();
$i=0;
foreach($users作为$user){
$i++;
//做事
}
//停止输出缓冲区并以字符串形式获取循环输出
$loopOutput=ob_get_clean();
//按正确的顺序输出所有内容
回显“编号为“$i.”.$loopOutput;

也许可以尝试连接
$string
的第一个定义,就像这样:
$string=“数字是“$i.”
Erm。。。难道你不能用
echo'the number is.count($users)替换整个代码吗?为什么必须在循环内执行此操作,如果希望某件事情在最后只发生一次,则在循环外执行此操作更符合逻辑……在foreach循环中,变量$users是您的两倍。这不应该是foreach($users作为$user)
?@RPM:这行不通。谢谢,这正是我一直在寻找的解决方案。
// 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;