删除存在多个字符的行

时间:2017-02-20 09:03:39

标签: php

我正在使用file_get_contents读取文件。 有些行可以有多个“=”字符,我想删除这些行。

我试过

str_replace("=", "", $content);

但这取代了所有出现的“=”,但没有删除这些行。

请问好吗?

更新:我的文件内容如下所示:

something

apple is =greee= maybe red
sugar is white

sky is =blue

1 个答案:

答案 0 :(得分:0)

没有看到你的文件/字符串的例子,建议有点棘手,但我会努力的基本原则是这样的:

$FileName = "PathToFile";
$FileData = file_get_contents($FileName);
$FileDataLines = explode("\r\n", $FileData); // explode lines by ("\n", "\r\n", etc)

$FindChar = "="; // the character you want to find

foreach($FileDataLines as $FileDataLine){
    $NoOfChar = substr_count($FileDataLine, $FindChar); // finds the number of occurrences of character in string
    if($NoOfChar <= 1){ // if the character appears less than two times
        $Results[] = $FileDataLine; // add to the results
    }
}
# print the results
print_r($Results);
# build a new file
$NewFileName = "YourNewFile";
$NewFileData = implode("\r\n", $Results);
file_put_contents($NewFileName, $NewFileData);

希望有所帮助