我有一个文本文件,其中包含每个项目之间的" 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);
?>
简单的答案,在保存之前,请在所有值上使用trim()
:
'type' => trim($exploded[1]),
但是,这项工作是您可以通过正则表达式更有效地做的事情。还要注意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()
相反;也就是说,它采取了参数,并将这些名称的变量放入关联数组中。