使用php更改一行文本文件中的单词

时间:2013-05-02 13:45:40

标签: php file preg-replace

我需要在 Maildir 之后更改单词,在这行的 NULL 中:(单词NULL可以是任何单词。)

  [3]=>
  string(42) "SPAM
* ^Subject: \[SPAM\].*
Maildir/.NULL/"

我使用此代码:

if($filecontent = file_get_contents($filename)){

    $repertoire = "SPAM";
    $tab = explode("#", trim($filecontent));
    $tab[3] = preg_replace("#Maildir/*#", 'Maildir/.'.$repertoire.'/', $tab[3]);

    var_dump($tab);

但我有

  string(48) "SPAM
* ^Subject: \[SPAM\].*
Maildir/.NULL/.SPAM/"

如何在 Maildir / .SPAM 中更改,因为 .NULL 过多。

  string(48) "SPAM
* ^Subject: \[SPAM\].*
Maildir/.SPAM/"

1 个答案:

答案 0 :(得分:0)

你可以这样做:

 preg_replace('~Maildir/\K\.NULL/(?=\.SPAM)~', '', $string);

或任何字词:

 preg_replace('~Maildir/\K[\w.-]++/(?=\.SPAM)~', '', $string);

我测试过:

$string = <<<LOD
SPAM
* ^Subject: \[SPAM\].*
Maildir/.NULL/.SPAM/
LOD;
echo preg_replace('~Maildir/\K[\w.-]++/(?=\.SPAM)~', '', $string).'<br/>';
echo preg_replace('~Maildir/\K\.NULL/(?=\.SPAM)~', '', $string).'<br/>';