我有一個PHP腳本,我用它來解析一些純文本到CSV格式。解決PHP解析純文本?
<?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]視爲新條目,而不是連接到前一個數組。任何人都可以幫我解決這個問題。這將不勝感激!
忽略顏色。我不想讓他們表現出來。 – user2483916
@Robert你能幫忙解釋一下嗎?我相當新手PHP腳本。 – user2483916
你想要什麼輸出格式? –