简体   繁体   中英

PHP replace last x character in console

I want to replace last x character from console output. I can remove complete line by using \\r . But is there a way to just remove last x character from console output ?

In PHP :

To print a backspace character, use 0x08 . BUT, there's a problem. If you follow that by a newline "\\n" (which you normally would) then the cursor is moved back to EOL, and the characters are exposed again. Good news is that if you follow the 0x08 with the same number of spaces, it works fine. For example, to remove the last two characters:

<?php
    print "Hello";
    printf("%c%c",0x08,0x08);
    print "  \n";
?>

Which prints Hel . Note the use of printf() with %c to use an integer (0x08) as a character.

For a generic way to remove x number of characters:

<?php
    $x = 4;
    $str = "Those who are about to die salute you";
    $hacky = str_repeat(chr(0x08),$x).str_repeat(" ",$x);
    print "$str$hacky\n";
?>

which prints Those who are about to die salute . Note the use of chr(0x08) here, which returns the character at position 8 in the character set.

您可以使用cut命令。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM