プレーンテキストをCSV形式に解析するために使用しているphpスクリプトがあります。
<?php
$text = "1. Bonus: Name some things about US history. For 10 points each:
[10] Name the first president of the United States of America.
ANSWER: George Washington
[10] How many original colonies were there?
ANSWER: 13
[10] How many states exist today?
ANSWER: 50";
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( '/^\[10\](.+?)$/', $line, $quest ) ) {
$temp[] = trim( $quest[0] );
continue;
}
if ( preg_match( '/^([0-9]+)\.(.+?)$/', $line, $quest ) ) {
$temp[] = trim( $quest[1] );
$temp[] = trim( $quest[2] );
continue;
}
if ( preg_match( '/^ANSWER\:(.+?)$/', $line, $quest ) ) {
$temp[] = trim( $quest[1] );
$data[] = "|".implode( '|,|', $temp )."|";
$temp = array();
}
}
return implode( "\r\n", $data );
}
echo text_to_csv( $text );
?>
これは以下を返します:
|1|,|Bonus: Name some things about US history. For 10 points each:|,|[10] Name the first president of the United States of America.|,|George Washington|
|[10] How many original colonies were there?|,|13|
|[10] How many states exist today?|,|50|
2 番目と 3 番目の [10] は別の行にあり、最初の行とは一致しません。私が出力したいのは次のとおりです。
|1|,|Bonus: Name some things about US history. For 10 points each:|,|[10] Name the first president of the United States of America.|,|George Washington|,|[10] How many original colonies were there?|,|13|,|[10] How many states exist today?|,|50|
文字列全体がすべて 1 行にあり、コンマで区切られています。スクリプトが 2 番目と 3 番目の [10] を前の配列に接続するのではなく、新しいエントリとして扱っていることが原因だと思います。誰でもこれを修正するのを手伝ってくれますか? それは大歓迎です!