我有一个 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
2. Bonus: Name some stuff. For 10 points each:
[10] What does lol mean?
ANSWER: Laugh Out Loud
[10] What is the capital of Virginia?
ANSWER: Richmond
[10] What language am I writing in?
ANSWER: PHP";
function text_to_csv( $text = null ) {
$lines = explode( "\n", $text );
$data = null;
foreach( $lines as $line ) {
$line = trim( $line );
if ( empty( $line ) ) {
continue;
}
if ( preg_match( '/^\[10\](.+?)$/', $line, $quest ) ) {
$data .= "|".trim( $quest[0] )."|,";
}
if ( preg_match( '/^([0-9]+)\.(.+?)$/', $line, $quest ) ) {
$data .= "|".trim( $quest[1] )."|,";
$data .= "|".trim( $quest[2] )."|,";
}
if ( preg_match( '/^ANSWER\:(.+?)$/', $line, $quest ) ) {
$data .= "|".trim( $quest[1] )."|,";
}
}
return rtrim($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|,|Bonus: Name some stuff. For 10 points each:|,|[10] What does lol mean?|,|Laugh Out Loud|,|[10] What is the capital of Virginia?|,|Richmond|,|[10] What language am I writing in?|,|PHP|
整个字符串在一行上。我希望它在每个“奖金”集之后中断(像这样):
|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|,|Bonus: Name some stuff. For 10 points each:|,|[10] What does lol mean?|,|Laugh Out Loud|,|[10] What is the capital of Virginia?|,|Richmond|,|[10] What language am I writing in?|,|PHP|
这样,每个“奖励”集都位于单独的行中,并且在每一行中,段由逗号分隔(CSV 格式)。谁能帮我完成这个。我真的很感激。我对解析和正则表达式相当陌生。