$/e','',$string); echo $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;
}
?>
它将foreach
循环迭代的次数附加到$string
中,而我只希望它在循环结束时显示为The number is 4
一次。如果在循环之外,则preg_replace
可以工作。如何对输出执行一次echo
操作并删除其余内容。我需要在循环中完成,而不是在循环之外。
发布于 2012-06-28 11:57:19
这样就可以了:
$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
复杂得多。如果不是,可以考虑简化一些事情。
发布于 2012-06-28 12:04:00
我认为您需要的解决方案是output buffering
// 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;
https://stackoverflow.com/questions/11243827
复制相似问题