Andrey
Andrey

Reputation: 859

PHP Remove line containing string from a text file

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!

Upvotes: 1

Views: 9697

Answers (3)

Baba
Baba

Reputation: 95101

  • You can use trim to remove all white spaces
  • file can read all the content as array
  • You can use array_map to apply trim to all array content
  • You can use in_array to check element of an array

Example

$fileContents = array_map("trim",file("hi.test"));
var_dump($fileContents);

Output

array
  0 => string 'Kate' (length=4)
  1 => string 'Johnny' (length=6)
  2 => string 'Bill' (length=4)
  3 => string 'Kermit' (length=6)

To check if Bill is there

if(in_array("Bill", $fileContents))
{
    //Bill is here 
}

Upvotes: 1

Arun Killu
Arun Killu

Reputation: 14233

while(!feof($file)){
   $stringData = fgets($file);//read a line on every itration

if (strpos($stringData , "Bill") !== false) {
//do somting
}

}

Upvotes: 0

Adam Plocher
Adam Plocher

Reputation: 14233

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

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

Upvotes: 2

Related Questions