解析此数据的建议

时间:2010-10-06 06:22:21

标签: php parsing

所以我有一个庞大的名称文件,必须拆分为更多的Excel列。

所以我使用PHP来解析它,所以这是示例的一部分:

Dr. Johnny Apple Seed
Ms. A. P. Oranges
Mrs. Purple Cup

基本上,我想把它放到一个数组中。我正在使用fopen,fget和explode。问题是,如果我使用explode,一些数组将不具有一致的元素。例如,第一个将有4个(Dr,Johnny,Apple,Seed),第三个只有3个。如何在紫色和杯子之间添加第四个空元素?还是有更好的方法?

这是我的代码:

$fp = fopen($filename,"r");

if ($fp) { 
   while (!feof($fp)) { 
  $data = fgets($fp, filesize($filename));
  $contents[] = explode(" ", $data) . 
   } 

} 

fclose($fp);
echo "<pre>";
var_dump($contents);
echo "</pre>";

期望的输出:

  array(4) {
    [0]=>
    string(4) "Mrs."
    [1]=>
    string(4) "Purple"
    [2]=>
    string(1) " "
    [3]=>
    string(8) "Cup"

array(4) {
    [0]=>
    string(3) "Dr."
    [1]=>
    string(6) "Johnny"
    [2]=>
    string(5) "Apple"
    [3]=>
    string(4) "Seed"

4 个答案:

答案 0 :(得分:1)

试试这个(尚未测试但应该有效):

// Define the clean array
$clean_array = array();

$fp = fopen($filename,"r");
if ($fp) { 
    while (!feof($fp)) { 
        $data = fgets($fp, filesize($filename));
        // use trim() on $data to avoid empty elements
        $contents = explode(" ", trim($data));

        if (count($contents) == '3') {
            // Copy last element to new last element
            $contents[] = $contents[2];
            // Clear the old last element
            $contents[2] = ' ';
        }
        $clean_array[] = $contents;
    } 
} 
fclose($fp);

echo '<pre>';
print_r($clean_array);
echo '</pre>';

希望这有帮助。

答案 1 :(得分:1)

这应该有效:

<?php
$new_array = array();
$fp = fopen($filename, "r");
if ($fp) {
    while (!feof($fp)) {
        $data = fgets($fp, filesize($filename));
        $contents[] = explode(" ", $data);
    }
}
foreach ($contents as $content) {
    if (count($content) != 4) {
        $content[3] = $content[2];
        $content[2] = " ";
        $new_array[] = $content;
    }
    else {
        $new_array[] = $content;
    }
}
fclose($fp);
echo "<pre>";
var_dump($new_array);
echo "</pre>";
?>

答案 2 :(得分:0)

如果它们是换行符,您可以使用“\ n”作为$ needle

答案 3 :(得分:0)

我使用了array_splice,这是我的解决方案:

<?php

$filename = "excel-names.txt";
$fp = fopen($filename,"r");

if ($fp) { 
   while (!feof($fp)) { 
        $data = fgets($fp, filesize($filename));
        $contents[] = explode(" ", $data, 4);
    }    
} 

fclose($fp);

foreach( $contents as $a) {
    $arrayCount = count($a);

    if( $arrayCount == 3 ) {
        array_splice($a, 2, 0, " ");
    }
    if( $arrayCount == 2 ) {
        array_splice($a, 0, 0, " ");
        array_splice($a, 2, 0, " ");
    }
}

?>