[英]How to remove a line from text file using php with specific structure
我有一個具有以下內容的CSS文件:
#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; }
如何使用php刪除所有#firstdiv
CSS屬性?
這是我想要的輸出:
#seconddiv { width:80%; height:70px; }
#thirddiv { width:80%; height:70px; }
#seconddiv { color:red; background:green; }
最簡單的方法是根據換行符分割文件,然后檢查每一行是否以您不需要的字符串開頭,最后將文件保存到該位置。
$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);
如果一行上有多個選擇器,則需要執行此操作
$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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.