如何在PHP中将托架返回到上一行

时间:2014-08-29 07:33:28

标签: php

\r会将我的指针移动到行的开头,但是如何返回上一行?

e.g。来自代码:

echo "First Line \n";
echo "Second Line \n";
ReturnToPreviousLine();
echo "Third Line \n"; 

$ php script.php

执行

我想在控制台中输出:

Third Line
Second Line

也许我会添加更好的例子:

  echo "Hello World!\n"
  //some loop
    echo "Time        Percent\n";
    echo "\r$time       $percent";
  //end loop
  returnToPreviousLine();
  echo "Done                 \n";
  echo "                     \n";

循环期间的输出:

Hello World!
Time        Percent
00:00:10    10%

循环后输出:

Hello World!
Done

2 个答案:

答案 0 :(得分:5)

您可以使用ANSI终端控制字符实现此视觉输出。我曾为此写过一个库,它在Github上:Jm_Console。我建议使用PEAR安装它(因为它会为你处理依赖)

以下是一个如何使用它的示例:

require_once 'Jm/Autoloader.php';

// Will refactor the Singleton pattern once :)
$console = Jm_Console::singleton();

// Save the cursor position before printing the first line
$console->savecursor();

// Output the first and second line
$console->writeln('First Line');
$console->writeln('Second Line');

// Sleep a second ...
sleep(1);

// Return back to the first line
$console->restorecursor();

// Erase the first line
$console->stdout()->eraseln();

// Print the third line (And the second line again, unfortunately)
$console->writeln('Third line');
$console->writeln('Second line');

答案 1 :(得分:-1)

你可以尝试使用output buffering AFAIK,如果你在拨打echo时没有使用它,那么你就无法撤消它。

所以诀窍是使用输出缓冲,然后在再次输出之前,挂钩到输出中以改变你想要的东西:

<?php

ob_start();

echo "First line\n";
echo "Second line\n";
echo "Third line\n";

$output = ob_get_clean();

$lines = explode("\n", $output);

print_r($lines);

// Outputs:
Array
(
    [0] => First line
    [1] => Second line
    [2] => Third line
    [3] =>
)

从这里开始,你的输出将在$ lines数组中,然后你可以echo你想要的任何一行