简体   繁体   中英

change a word in a line of text file with php

I need to change the word just after Maildir , in this exemple NULL of a line : (the word NULL can be any word.)

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

I use this code :

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

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

    var_dump($tab);

But i have

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

How can i change that in Maildir/.SPAM because .NULL is in excess.

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

You can do like this:

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

or for any word:

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

I have tested with:

$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/>';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM