How do I erase printed characters in a console application(Linux)?

I don't think you need to apologize for the language choice. PHP is a great language for console applications.

Try this out:

<?php
for( $i=0;$i<10;$i++){
  print "$i \r";
  sleep(1);
}
?>

The "\r" will overwrite the line with the new text. To make a new line you can just use "\n", but I'm guessing you already knew that.

Hope this helps! I know this works in Linux, but I don't know if it works in Windows or other operating systems.


To erase a previously printed character you have three options:

  • echo chr(8) . " "; echoes the back character, and will move the cursor back one place, and the space then overwrites the character. You can use chr(8) multiple times in a row to move back multiple characters.

  • echo "\r"; will return the cursor to the start of the current line. You can now replace the line with new text.

  • The third option is to set the line and column of the cursor position using ANSI escape codes, then print the replacement characters. It might not work with all terminals:

  function movecursor($line, $column){
      echo "\033[{$line};{$column}H";
  }

\r did the trick.

For future reference, \b does not work in PHP in Linux. I was curious - so I did a couple of experiments in other languages as well(I did this in Linux - I don't know if the result will be the same in Windows/Mac)..

\b Works in...

  • Perl
  • Ruby
  • Tcl - with code puts -nonewline "Hello\b"

\b Doesn't work in

  • PHP - the code print "Hello\b"; prints out Hello\b
  • Python - code print "Hello\b" prints out Hello<new line> . Same result with print "Hello\b",