PHP中readline()输入时退格清空内容后整行被清除的问题求助
I’ve run into this exact annoyance before—using fwrite to print a prompt then readline() leads to wonky backspace behavior because readline doesn’t know about the prompt you manually wrote. Here’s how to fix it:
The Simplest Fix: Use readline()’s Built-in Prompt
Instead of writing the prompt with fwrite, pass it directly as an argument to readline(). This lets readline manage the prompt properly, so it knows exactly where user input starts and stops. Backspacing will only erase the user’s input, not the prompt itself.
$response = readline('Would you like some apple pie? [y/N]');
Why the Original Code Causes the Problem
When you use fwrite(STDOUT, ...) to output the prompt, that text is just dumped to the terminal—readline() has no awareness of it. So when you backspace all your input characters, readline keeps deleting characters backward into the prompt text, making the whole line disappear. By letting readline() handle the prompt, it tracks the boundary between the prompt and your input, preventing accidental prompt deletion.
Alternative: For Advanced Prompt Control
If you need more control over the prompt (like colored text or dynamic updates), you can use readline_callback_handler_install() which gives you finer-grained control over the input process. Here’s a quick example:
$prompt = 'Would you like some apple pie? [y/N]'; // Install the callback handler readline_callback_handler_install($prompt, function($input) { echo PHP_EOL . "You entered: $input" . PHP_EOL; readline_callback_handler_remove(); }); // Wait for input while (true) { $r = [STDIN]; $w = null; $e = null; if (stream_select($r, $w, $e, null) && in_array(STDIN, $r)) { readline_callback_read_char(); break; } }
This approach keeps readline in charge of the prompt, so backspacing behavior stays consistent with other command-line tools.
内容的提问来源于stack exchange,提问作者Patriot

