【问题标题】:Fix for PHP parsing script output?修复 PHP 解析脚本输出?
【发布时间】:2013-06-25 16:23:59
【问题描述】:

我有一个 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 格式)。谁能帮我完成这个。我真的很感激。我对解析和正则表达式相当陌生。

【问题讨论】:

  • P.S.我选择用“|”将字段括起来而不是引号,因为我将使用的某些字段实际上包含引号,并且以这种方式更容易上传到 MySQL 数据库。
  • 根据您的输入结构,您可能希望在遇到空行或x. Bonus 标记时进行拆分。这应该不难 - 在这种情况下只需添加一个新行。
  • @KarolPiczak 在每个奖金之间是一个空行,那么我将如何编码以在空行上拆分?

标签: php regex parsing csv


【解决方案1】:

评论太长了,但回答的时间还不够长。

如果要在空行处拆分:

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

应该变成:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-04
    • 2013-06-21
    • 1970-01-01
    • 2021-03-21
    • 1970-01-01
    • 2019-03-23
    • 2016-04-28
    • 1970-01-01
    相关资源
    最近更新 更多