Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I echo a backspace from php cli?

This question: https://askubuntu.com/questions/16149/overwrite-previous-output-in-bash-instead-of-appending-it

Explains how to do a countdown as a bash script. I want to do the same thing, but I need to do it in PHP. Is there a way to echo a backspace?

e.g.

echo "Counting down 60\n";
sleep(1);
echo "\b\b\b59\n";
sleep(1);
echo "\b\b\b58\n";

But, echo "\b" doesn't do anything.

like image 415
Benubird Avatar asked Mar 01 '13 12:03

Benubird


2 Answers

From Strings - Double quoted, there is no \b recognized as an escape sequence. You can use the ASCII backspace hex or octal code

$bs = "\x08";
echo "Counting down 60";
sleep(1);
echo "$bs$bs59";
sleep(1);
echo "$bs$bs58";

or in a loop all the way down to zero

$bs = "\x08";
for ($i = 59; $i >= 0; --$i) {
    sleep(1);
    printf("$bs$bs%2d", $i);
}

You must omit the newline \n as well.

like image 59
Olaf Dietsche Avatar answered Nov 07 '22 02:11

Olaf Dietsche


The backspace character corresponds to the ASCII character code 8, so you can output it using PHP's char() function.

Ex. if you do something like:

echo 'Hello, world!' . chr(8);

The resulting output is:

Hello, world
like image 8
Liv Avatar answered Nov 07 '22 01:11

Liv