使用explosion拆分数组值


Split array values using explode

我需要在$str中使用白色空间的爆炸功能,在将文本文件的内容加载到$str后,但它似乎不起作用:

$filename='acct.txt';
$str=file_get_contents($filename);
print_r (explode("'t",$str));
输出:

Array ( [0] => 101 [1] => 345.23 102 [2] => 43.2 103 [3] => 0 104 [4] => 33 )
print_r (explode(" ",$str));
输出:

Array ( [0] => 101 [1] => 345.23 102 [2] => 43.2 103 [3] => 0 104 [4] => 33 ) 

文件包含如下内容:

101 345.23
102 43.2
103 0
104 33

我应该如何改变它一次得到一个元素?即:

Array ( [0] => 101 [1] => 345.23  [2] => 102 ....[8]=>33) 

谢谢你的帮助!

答案是,如果你有多个分隔符(换行符和空格),你必须使用preg_split函数而不是爆炸。所以你的代码应该是这样的:

$filename='acct.txt';
$str=file_get_contents($filename);
print_r (preg_split( '/( |'r'n|'r|'n)/', $str ));

它将输出:

Array ( [0] => 101 [1] => 345.23 [2] => 102 [3] => 43.2 [4] => 103 [5] => 0   [6] => 104 [7] => 33 )
编辑:

虽然上面的正则表达式工作得很好,但使用下面的东西要简单得多:

preg_split( '/('s+)/', $str )

具有完全相同的输出,但是更加优雅。

您可以使用fgets()逐行读取文件。获取一行数组,然后将其平展。可能有更多的快捷方式,但这对我来说是可行的。

<?php
function flatArray($array) {
 $arrayValues = array();
 foreach (new RecursiveIteratorIterator( new RecursiveArrayIterator($array)) as $val) {
  $arrayValues[] = $val;
 }
 return $arrayValues;
}
$handle = fopen("acct.txt", "r");//YOur file location
$rows = array();
if ($handle) {
    while (($str = fgets($handle)) !== false) {
        // process the line read.
        $rows[] = explode(" ",$str);
    }
    fclose($handle);
} else {
    // error opening the file.
} 
$flatarray = flatArray($rows);

var_dump($flatarray);