How to remove a line from text file using php with specific structure

421 views Asked by At

I have a css file with this content:

#firstdiv { width:100%; height:200px; }
#seconddiv { width:80%; height:70px; }
#thirddiv { width:80%; height:70px; }
#firstdiv { color:red; background:yellow; }
#seconddiv {  color:red; background:green; }
#firstdiv { border:3px solid black; border-rdius:5px; }

How can I remove all #firstdiv css properties using php?

This is my desired output:

#seconddiv { width:80%; height:70px; }
#thirddiv { width:80%; height:70px; }
#seconddiv {  color:red; background:green; }
1

There are 1 answers

6
rrr On

The most easy way would to split the file based on newlines and then check for each row whether it starts with the string you don't want and finally save the file to the location.

$filelocation = "/path/to/file"; //please update for your situation
$csscontents = file_get_contents($filelocation);
$lines = explode(PHP_EOL,$csscontents);
$csscontents = '';
foreach($lines as $line) {
    if (substr($line,0,9) !== "#firstdiv") $csscontents .= $line . PHP_EOL;
}
file_put_contents($filelocation,$csscontents);

In case there are multiple selectors on one line, you need to do this

$filelocation = "/path/to/file"; //please update for your situation
$csscontents = file_get_contents($filelocation);
$lines = explode('}',$csscontents);
$csscontents = '';
foreach($lines as $line) {
    if (substr(preg_replace('/\s+/', '',$line),0,9) !== "#firstdiv" AND !empty($line) AND !ctype_space($line)) $csscontents .= $line . "}";
}
file_put_contents($filelocation,$csscontents);