修复PHP解析脚本输出


Fix for PHP parsing script output?

我有一个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格式)分隔。有人能帮我完成这件事吗。我真的很感激。我对解析和正则表达式还很陌生。

注释太长,但实际上还不够长。

如果你想在空行拆分:

if ( empty( $line ) ) {
    continue;
}

应更改为:

if ( empty( $line ) ) {
   $data .= "'n";
   continue;
}