Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/242.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP-填充stdin整数输入的数组_Php_Arrays - Fatal编程技术网

PHP-填充stdin整数输入的数组

PHP-填充stdin整数输入的数组,php,arrays,Php,Arrays,例如: $_fp = fopen("file.txt", "r"); /* STDIN = "4 7 6 24 1"; */ <== user input $input[] = fgets($_fp); print_r($input); 期望输出: Array ( [0] => 4 [1] => 7 [2] => 6 [3] => 24 [4] => 1 ) 在数组中输入空格后,是否有任何方法可以从整数输入中删除空

例如:

$_fp = fopen("file.txt", "r");
/* STDIN = "4 7 6 24 1"; */ <== user input

$input[] = fgets($_fp);
print_r($input);
期望输出:

Array
(
    [0] => 4
    [1] => 7
    [2] => 6
    [3] => 24
    [4] => 1
)
在数组中输入空格后,是否有任何方法可以从整数输入中删除空格? 以避免将整个输入作为一行

我使用了
$input[]=explode(“”,trim(fgets($\u fp))现在,当有第二行时,它只会将STDIN的第一行放入,我需要读取所有行并将它们放入输入变量中

while($f=fgets(STDIN)){echo“line:$f”}
在这里非常有用 可以回显所有行,但还不能将每行指定给变量或数组。。不确定是否应该
array\u push()
,因为我需要2行作为变量,其余作为数组。

使用trim删除行的“\n”,使用explode将其转换为数组

如果有更多行,请使用以下命令:

$input[] = explode(' ', trim(fgets($_fp)));

即使我们可以尝试preg_match_all with regx,在所有情况下也会得到相同的结果,比如在整数字符串之间有双空格或任何文本

$string = "4   7  6  24 1";
$string = "4 test df 7 6 24 1"; 
$string = "4 7 6 24 1";
preg_match_all('!\d+!', $string, $matches);

print_r($matches);

它的作品!但是通过$input而不是$input[0]访问值是否有效,因为。打印(输入);数组([0]=>Array([0]=>4[1]=>7[2]=>6[3]=>24[4]=>1))例如$sum=Array\u sum($input);=//0I提供两个版本,如果只有一行,请使用第一行。
$input[] = explode(' ', trim(fgets($_fp)));
$string = "4   7  6  24 1";
$string = "4 test df 7 6 24 1"; 
$string = "4 7 6 24 1";
preg_match_all('!\d+!', $string, $matches);

print_r($matches);