使用PHP将纯文本解析为CSV?

时间:2013-06-24 20:10:03

标签: php parsing csv plaintext

我有一个纯文本文件(.txt),包含琐事问题,格式如此(小样本):

1. Who was the first president of the United States of America?
ANSWER: George Washington

2. What is the opposite of up?
ANSWER: Down

3. What country's capital is Paris?
ANSWER: France

问题#和问题在一行上,答案是在实际答案前面带有“ANSWER:”标记的下一行。

我想获取此数据并将其转换为CSV,其中列为问题#,问题和答案,如下所示:

"1","Who was the first president of the United States of America?","George Washington"
"2","What is the opposite of up?","Down"
"3","What country's capital is Paris?","France"

注意:问题#之后的句点和答案前的“ANSWER:”标记将被删除。

如何在PHP脚本中执行此操作,该脚本采用纯文本数据并输出CSV,如上所示?我完全不熟悉解析(我认为这就是它的名称?),非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

实际上我的代码非常简单,但它可以工作:)

<?php
  $text = '1. Who was the first president of the United States of America?
ANSWER: George Washington

2. What is the opposite of up?
ANSWER: Down

3. What country\'s capital is Paris?
ANSWER: France';

echo text_to_csv( $text );

function text_to_csv( $text = null ) {
  $lines  = explode( "\n", $text );
  $data   = array();
  $temp   = array();
  foreach( $lines as $line ) {
    $line = trim( $line );
    if ( empty( $line ) ) {
      continue;
    }
    if ( preg_match( '/^([0-9]+)\.(.+?)$/', $line, $quest ) ) {
      $temp[] = trim( $quest[1] );
      $temp[] = trim( $quest[2] );
      continue;
    }
    if ( preg_match( '/^answer\:(.+?)$/i', $line, $quest ) ) {
      $temp[] = trim( $quest[1] );
      $data[] = '"'.implode( '","', $temp ).'"';
      $temp = array();
    }
  }
  return implode( "\n", $data );
}
?>