PHP循环在csv上 - 在Regex模式下的开始和结束循环

时间:2011-08-11 16:38:06

标签: php regex loops csv

我需要将csv文件打印成html或将数字数据放入数据库:
但我需要在特定位置开始循环并将其分解到另一个特定位置(正则表达式) 因此,我只需要重新打印包含数字数据的行和来自它们的所有列 以下是伪代码 - 无法正常工作:

<?php
$row = 1;
$handle = fopen("test.csv", "r");
while ($data = fgetcsv($handle, 1000, ","))
{
   if (preg_match('/[Morning]/', $data[0]) === 1 // start at this rwo plus two lines down )
    {
    $num = count($data);
    $row++;
      for ($c=0; $c < $num; $c++)
      {
            for ($c=0; $c < $num; $c++)
            {  
              echo $data[$c] . " ";
            }   
      if (preg_match('/[Total Cash:]/', $data[0]) === 1)
        { break; row -1 }            
      }
       echo "<br>";  
   }
}
fclose($handle); ?>

所以csv是这样的:

/--some lines--/

Date: 3/3/11, Morning, --blank line--- Customer No,Time,CheckNo,Total, 1234,12-45,01,20.00, 1236,1-00,03,30.00, 1240,2-00,06,30.00, --more numerical rows of data at variable length that I need to loop over-- 1500,4-00,07,22.00, ----,----,---,----, Total Cash, , , ,120.00,

/--some other lines--and it goes/

Lunch Time, ---similar like Morning above ---

任何关于如何正确地添加这个问题的信息都很感激,我现在​​可以做很多循环和正则表达式,但有了这个,我需要更多的时间和帮助。感谢。

3 个答案:

答案 0 :(得分:0)

$lines = file('test.csv'); //read file into an array, one entry per line

$active = false; //keep track of what rows to parse

//loop one line at a time
for ($i = 0; $i < count($lines); $i++) {
  $line = $lines[$i];

  if (strpos($line, 'Morning') !== false) { //start parsing on the next row
    $active = true;
    $i += 2; //skip the blank line and header
    continue;
  }
  if (strpos($line, '----,') !== false) { //stop parsing rows
    $active = false;
  }

  if ($active) { //if parsing enabled, split the line on commas and do something with the values
    $values = str_getcsv(trim($line));
    foreach ($values as $value) {
      echo $value . " "; //these are the numbers
    }
  }

}

答案 1 :(得分:0)

$lines = file('test.csv');
$parsing = false;
foreach ($lines as $line)
{
    $parsing = ((strpos($line, 'Morning') !== false) || $parsing)
        && ((strpos($line, 'Total Cash') === false);

    if (!$parsing)
        continue;

    $values = strgetcsv($line);
    echo implode(' ', $values);
}

编辑:基本上,它与Dan Grossmans解决方案相同,但更短; - )

答案 2 :(得分:0)

$lines = file('test.csv');

// Skip the unwanted lines
// Means: Every line until the line containing "Morning,"
do {
    $line = array_shift($lines);
} while(trim($line) !== 'Morning,');
$lines = array_slice($lines, 2); // Mentioned something about "2 lines below" or such" ^^

// Do something with the remaining lines, until
// Line _begins_ with "Total Cash"
while(strncmp('Total Cash', trim($line = array_shift($lines)), 10) !== 0) {
    echo implode(' ', str_getcsv($line)) . PHP_EOL;
}