从文件中剪切文本

时间:2014-03-19 10:01:29

标签: php file

我有以下文本文件:

::: Student Exam :::
Name: John Cage
Score: 5
Witness: Maria McCain
::: End Exam :::

::: Student Exam :::
Name: John Cage
Score: 5
Witness: Calvin Gilbert
::: End Exam :::

我正在使用此代码解析它:

$db = file_get_contents(dirname(__FILE__) . '/exams.txt', TRUE);
$nl = "\r\n";

preg_match_all("|::: Student Exam :::(.*?)::: End Exam :::|s", $db, $exams);

foreach($exams[1] as $exam) {
    preg_match("|Name: (.*?)$nl|s", $exam, $name);
    preg_match("|Score: (.*?)$nl|s", $exam, $score);
    preg_match("|Witness: (.*?)$nl|s", $exam, $witness);

    if($score[1] < 4) {
        // Something Here
    }
}

我需要,如果分数低于4,则必须从文件中删除考试。如何做到这一点?

1 个答案:

答案 0 :(得分:0)

创建一个空数组

$goodExams = array()

将考试推进其中:

if($score[1] >= 4) {
    $goodExams[] = $exam;
}

或者:

if($score[1] >= 4) {
    $goodExams[] = array('name' => $name[1], 'score'=>$score[1], 'witness'=>$witness[1]);
}

$newTxt = "";
foreach($goodExams as $exam){
    $newTxt.="::: Student Exam :::" . PHP_EOL;

    // concatenae your data here

    $newTxt.="::: End Exam :::" . PHP_EOL;
}

file_put_contents($filename, $newTxt)

之后,您可以处理goodExams数组并转储文本文件。