0

我有一个纯文本文件 (.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,如上所示?我对解析完全陌生(我认为这就是所谓的?)并且非常感谢任何帮助。

4

1 回答 1

1

In fact my code is really simple, but it will work :)

<?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 );
}
?>
于 2013-06-24T20:22:27.677 回答