如何在PHP

时间:2017-03-09 21:47:52

标签: php multidimensional-array removing-whitespace

我有一个文本文件,其中包含以“\ n”分隔的行和每个项目之间的空格。项目由一个或多个空格分隔。但是,元素之间的空白间距在每一行都是一致的。

FRUIT   WATER   GRE  LRG   0003 050
FRUIT   BANAN   YEL  MED   0017 010
FRUIT   STRAW   RED  SML   0005 005
FRUIT   LEMON   YEL  SML   0024 005
VEGIE   REDPE   RED  MED   0008 001
VEGIE   GRENP   GRE  MED   0009 001
BOX   RED     006 012 018
BOX   YEL     010 020 030
BOX   GRE     003 006 009
PERSON      JOHN  TALL  STRG
PERSON      JIMM  MEDM  WEAK
PERSON      DAVD  MEDM  STRG

我试图用PHP解析这个文件。以下代码生成一个包含许多空格的数组。

if(file_exists($filename)) {
        $filecontents = file_get_contents($filename);
        $lines = explode("\n", $filecontents);
        foreach ($lines as $line) {
        $exploded = explode(" ", $line);
        if (sizeof($exploded) >= 5 and $exploded[0] == 'FRUIT') $array[] = array(
            'type' => $exploded[1],
            'color' => $exploded[2],
            'size' => $exploded[3],
            'qty' => $exploded[4],
            'weight' => $exploded[5]
            );
        if (sizeof($exploded) >=5 and $exploded[0] == 'VEGIE') $array[] = array(
            'type' => $exploded[1],
            'color' => $exploded[2],
            'size' => $exploded[3],
            'qty' => $exploded[4],
            'weight' => $exploded[5]
            );
        if (sizeof($exploded) >= 5 and $exploded[0] == 'BOX') $array[] = array(
            'color' => $exploded [1],
            'largefit' => $exploded[2],
            'medfit' => $exploded[3],
            'smallfit' => $exploded[4]
            );
        if (sizeof($exploded) >= 4 and $exploded[0] == 'PERSON') $array[] = array (
            'name' => $exploded[1],
            'build'=> $exploded[2],
            'strength' => $exploded[3]
            );
        }
    }

print_r($array);

?>

1 个答案:

答案 0 :(得分:0)

答案很简单,在保存之前对所有值使用trim()

'type' => trim($exploded[1]),

但是,通过regular expressions,您可以更有效地完成这项工作。另请注意,file()命令会自动将文件读入数组!

<?php
if(file_exists($filename)) {
    $array = [];
    $lines = file($filename);
    foreach ($lines as $line) {
        if (!preg_match("/(\w+)\s+(\w+)\s+(\w+)\s+(\w+)(?:(?:\s+(\w+))?\s+(\w+))?/", $line, $matches)) {
            continue;
        }
        switch ($matches[1]) {
            case "FRUIT":
            case "VEGGIE":
                list($foo, $bar, $type, $color, $size, $qty, $weight) = $matches;
                $array[] = compact("type", "color", "size", "qty", "weight");
                break;
            case "BOX":
                list($foo, $bar, $color, $largefit, $medfit, $smallfit) = $matches;
                $array[] = compact("color", "largefit", "medfit", "smallfit");
                break;
            case "PERSON":
                list($foo, $bar, $name, $build, $strength) = $matches;
                $array[] = compact("name", "build", "strength");
                break;
        }
    }
}
print_r($array);

compact()命令与extract()相反;也就是说,它接受它的参数,并将带有这些名称的变量放入一个关联数组中。