在问题发生时从 console/cli 读取输入值

Read input value from console/cli at the moment of the question

我在从 php 中创建的控制台应用程序读取输入命令时遇到问题。

问题

如果用户使用控制台错误地按了两次或更多次 ENTER 或一些字符,当进程正在加载时,在提问之前阅读命令然后跳过下一个.

我尝试了这些方法来捕获输入值,但我每次都发现同样的问题:

fgets(STDIN);
readline("Question: ");
stream_get_line(STDIN, 1024, "\n");

代码示例:

<?php
for($i = 0; $i < 15; $i++){
    $read = readline("Question $i: "); // Look at the number
    echo "Your answer is: " . $read . PHP_EOL;
    sleep(2); // Now on execution try press ENTER one ore more times
}

尝试次数

我试过了,但是这个方法对缓冲区不起作用(无论如何我都试过了):

$handle = fopen('php://stdin', 'r+');
ftruncate($handle, 0);
rewind($handle);
fclose($handle);
$read = readline("Question: ");

问题

如何在问题显示时读取并等待输入并丢弃之前的输入?

解决方案

我已经解决如下:

<?php
for($i = 1; $i < 10; $i++){
    /* BEGIN: SOLUTION */
    // Read/Clean buffer until isn't empty
    while(stream_select($read = [STDIN], $write = [], $except = [], 0)){
      fgets(STDIN);
    }
    /* END: SOLUTION */
    $read = readline("Question $i: "); // Look at the number
    echo "Your answer is: " . $read . PHP_EOL;
    sleep(2); // Now on execution try press ENTER one ore more times
}