且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PHP从文本文件中删除包含字符串的行

更新时间:2023-12-03 19:25:16

  $ var =Bill; 
$ input =Kate
Johnny
Bill
Kermit;

$ output = str_replace($ var。\r\\\
,,$ input。\r\\\
);


I have a file that looks something like this.

Kate
Johnny
Bill
Kermit

I want to be able to put, for example, "Bill" into a string, and remove "Bill", or whatever is in the variable, and the subsequent "\r\n" from the file. The variable will always contain something that is already in the file, there won't be "George" if there is no George.
This code checks if "Bill" is in file.

$fileContents = file_get_contents("names.txt");
if(strpos($fileContents, "Bill"))
{
    //Bill is here!
}

How would I expand upon this to remove "Bill\r\n"? Thanks in advance!

$var = "Bill";
$input = "Kate
Johnny
Bill
Kermit";

$output = str_replace($var ."\r\n", "", $input ."\r\n");