Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete text form textfile with php

I try to delete some texte in a text file.

The texte file is like that :

#MESSAGE
:0
* ^(To|cc).*fd.*
|/usr/bin/vacation fd
#monfiltreperso
:0
* ^From.*[email protected]
Maildir/.repertorymoi
#FIN
#monfiltreperso2
:0
* ^Subject:.*monsujet2
Maildir/.repertorymoi2
#FIN
#monfiltreperso3
:0
* ^From.*[email protected]
Maildir/.repertorymoi2
#FIN

I try to delete the line between #monfiltre... and #monfiltre...

I have this :

$pattern = '~'.'#filtre'.$nom.'\s*\n^#monfiltre~';
$filecontent = preg_replace($pattern, '', $filecontent);

So i can delete this line :

#monfiltreperso
:0
* ^From.*[email protected]
Maildir/.repertorymoi

But there is #FIN that is not deleted.

And i have :

 #MESSAGE
:0
* ^(To|cc).*fd.*
|/usr/bin/vacation fd
#FIN  (need to be deleted)
:0
* ^Subject:.*monsujet2
Maildir/.repertorymoi2
#FIN

I need to change this rules :

$pattern = '~'.'#filtre'.$nom.'\s*\n^#monfiltre~';

But I didn't find how.

like image 266
mpgn Avatar asked May 01 '26 23:05

mpgn


2 Answers

If you want to remove the portion between #monfiltre* until #FIN, you can use this expression:

echo preg_replace('/^#monfiltreperso$.+?^#FIN$[\r\n]*/ms', '', $str);

It uses the multiline mode /m so that you can match against ^ (start of line) and $ (end of line). To match across multiple lines, you need the dot-match-all mode /s; otherwise it will match until the end of each line.

An optional set of newline characters is matched as well to prevent empty lines from appearing in the end result.

Expression visualization

You can make it dynamic if you want:

$filter = preg_quote('perso3', '/');
echo preg_replace('/^#monfiltre' . $filter . '$.+?^#FIN$[\r\n]*/ms', '', $str);
like image 186
Ja͢ck Avatar answered May 03 '26 13:05

Ja͢ck


you can try this:

$pattern = '~#monfiltreperso\s*\n\K.+?(?=#monfiltreperso2)~s';
echo preg_replace($pattern, '', $texte);

or if you are sure to not have any # before #monfiltreperso2, you can use this:

$pattern = '~#monfiltreperso\s*\n\K[^#]++~';
like image 26
Casimir et Hippolyte Avatar answered May 03 '26 14:05

Casimir et Hippolyte



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!