我有一个 php 脚本,用于将一些纯文本解析为 CSV 格式。
<?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|
第二个和第三个 [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|
整个字符串都在一行上,并用逗号分隔。我认为正在发生的事情是脚本将第二个和第三个 [10] 视为新条目,而不是连接到前一个数组。任何人都可以帮我解决这个问题。这将不胜感激!