[英]How to remove multiple white spaces in a multiple line text file in PHP
我有一個文本文件,其中包含用“ \\ 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()
的相反; 也就是說,它接受參數,並將具有這些名稱的變量放入關聯數組中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.