PHP:为 STDIN/Single 字符处理添加箭头键支持

PHP: Adding Arrow Key Support to STDIN/Single Character Processing

在PHP中,我可以使用以下代码从命令行程序读取输入

$stream = STDIN;
$test = fgets($stream);
echo $test;

这适用于简单的输入。但是,如果我尝试使用类似后退箭头键的东西,我的 shell 看起来像下面的

This is a test^[[D^[[D^[[D    

^[[D的方向键转义序列被发送到shell。 PHP 本身会解释箭头键——即输入这个

This is a test^[[D^[[D^[[D^[[Dsecond test     

会输出这个

This is a second test

但是,我希望 shell 到 "correctly"(即做我认为他们应该做的,而不是我发送的字面意思)解释箭头键,以便插入点在键入时移动.

这在 PHP 中可行吗?有扩展吗?没有扩展名?我试过 fgets($stream, 1) 的变体,但似乎 PHP 只是挂起,直到用户输入回车键。

纯 PHP 没办法:http://php.net/fgetc(见评论)

有点棘手,但找到了使用 mbstring 库的方法:

// stream_set_blocking(STDIN, false); // Do not wait
while ($c = fread(STDIN, 16)) {
      $c = preg_replace('/[^[:print:]\n]/u', '', mb_convert_encoding($c, 'UTF-8', 'UTF-8'));
      /* Up arrow */
      if ($c === "[A"){
        echo "UP";     
      }
      /* Down arrow */
      if ($c === "[B"){
        echo "DOWN";
      }
      /* Right arrow */
      if ($c === "[C"){
        echo "RIGHT";
      }
      /* LEFT arrow */
      if ($c === "[D"){
       echo "LEFT";
      } 
  }

隐藏shell字符打印:

system("stty -echo");

在脚本结束时恢复:

stty echo