代码之家  ›  专栏  ›  技术社区  ›  Gagantous Faradox

从STDIN PHP中分割成数组的输入中排除空白值

  •  0
  • Gagantous Faradox  · 技术社区  · 6 年前

    我试图分割一个输入

    <?php
    $hand = fgets(STDIN);
    $hand_convert = str_split($hand);
    print_r($hand_convert);
    ?>
    

    我得到了这两个空值

    C:\xampp\htdocs\coding-test\Soal 1>php search.php
    asd
    Array
    (
        [0] => a
        [1] => s
        [2] => d
        [3] =>
        [4] =>
    
    )
    

    在数组末尾有两个附加的空白值。我相信我只输入了3个单词,但它返回5个索引。这两个空白的附加值来自哪里?

    我用 var_dump

    C:\xampp\htdocs\coding-test\Soal 1>php search.php
    asd
    array(5) {
      [0]=>
      string(1) "a"
      [1]=>
      string(1) "s"
      [2]=>
      string(1) "d"
      [3]=>
    " string(1) "
      [4]=>
      string(1) "
    "
    }
    

    我试着用 array_filter 但它仍然给了我两个空白值。

    <?php
    $hand = fgets(STDIN);
    $hand_convert = str_split($hand);
    print_r(array_filter($hand_convert));
    ?>
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   thyago stall    6 年前

    您可以尝试在拆分字符串之前调整值:

    <?php
    $hand = fgets(STDIN);
    $hand_convert = str_split(trim($hand));
    print_r($hand_convert);
    

    还有,你的尝试 array_filter 不起作用,因为此函数删除所有空的内容,换句话说,删除所有 empty() === true . AS empty("\n") === false 它没有移除。

    推荐文章