在 STDIN PHP 中从拆分为数组的输入中排除空白值
Exclude the blank value from an input that split into array in STDIN PHP
我尝试拆分输入
<?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 个单词,但它 return 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));
?>
您可以尝试在拆分字符串之前修剪您的值:
<?php
$hand = fgets(STDIN);
$hand_convert = str_split(trim($hand));
print_r($hand_convert);
此外,您对 array_filter
的尝试没有成功,因为此函数删除了所有空的内容,换句话说,删除了 empty() === true
的所有内容。由于 empty("\n") === false
它没有删除。
我尝试拆分输入
<?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 个单词,但它 return 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));
?>
您可以尝试在拆分字符串之前修剪您的值:
<?php
$hand = fgets(STDIN);
$hand_convert = str_split(trim($hand));
print_r($hand_convert);
此外,您对 array_filter
的尝试没有成功,因为此函数删除了所有空的内容,换句话说,删除了 empty() === true
的所有内容。由于 empty("\n") === false
它没有删除。