2013-06-24 108 views
0

我有一個格式包括小問題,像這樣(小樣本)的純文本文件(.txt):使用PHP解析純文本爲CSV?

1. Who was the first president of the United States of America? 
ANSWER: George Washington 

2. What is the opposite of up? 
ANSWER: Down 

3. What country's capital is Paris? 
ANSWER: France 

問題#和問題都在一行,得到的答覆是在在實際答案之前的下一行加上「ANSWER:」標籤。

我想借此數據,並將其轉換成CSV與柱有問題#,問題和答案,像這樣:

"1","Who was the first president of the United States of America?","George Washington" 
"2","What is the opposite of up?","Down" 
"3","What country's capital is Paris?","France" 

注:問題#和之後的時期「回答是:」標記在答案被刪除之前。

我會如何在一個PHP腳本中執行此操作,該腳本將如上所示接收純文本數據並輸出CSV?我完全不熟悉解析(我認爲這就是它的名字?),任何幫助都非常感謝。

+0

忽略的顏色代碼框。我不認爲這些會出現。 – user2483916

+0

由於它總是一個固定的格式,所以一個簡單的'fgets'和'substr'會讓你很好。 – deceze

+0

您將遍歷文件,解析每一行。看它是否有答案:或不。如果答案是肯定的:你可以將它除去並作爲第二列添加到一個數組中,如果它有一個#你會將它添加到第一列。然後把它發送給csv的東西。 – Steven

回答

1

其實我的代碼是非常簡單的,但它會工作:)

<?php 
    $text = '1. Who was the first president of the United States of America? 
ANSWER: George Washington 

2. What is the opposite of up? 
ANSWER: Down 

3. What country\'s capital is Paris? 
ANSWER: France'; 

echo text_to_csv($text); 

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('/^([0-9]+)\.(.+?)$/', $line, $quest)) { 
     $temp[] = trim($quest[1]); 
     $temp[] = trim($quest[2]); 
     continue; 
    } 
    if (preg_match('/^answer\:(.+?)$/i', $line, $quest)) { 
     $temp[] = trim($quest[1]); 
     $data[] = '"'.implode('","', $temp).'"'; 
     $temp = array(); 
    } 
    } 
    return implode("\n", $data); 
} 
?>