1

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!

Andrey
  • 849
  • 5
  • 17
  • 28

3 Answers3

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

$output = str_replace($var ."\r\n", "", $input ."\r\n");
Adam Plocher
  • 13,994
  • 6
  • 46
  • 79
  • If I just did `$output = str_replace($var ."\r\n", "", $input);` nothing seems to happen, but when I did `$output = str_replace($var ."\r\n", "", $input."\r\n");`, it left an empty line. I added `$newFile = substr($newFile, 0, -2); //Removes newline char` and now it works perfectly. Thanks! – Andrey Oct 04 '12 at 03:26
  • Ahh, good. You could also do a trim() to remove any trailing and leading whitespace. I appended an extra \r\n so it wouldn't fail to remove the last line. – Adam Plocher Oct 04 '12 at 03:28
  • I'll replace it with trim, just in case. It seems like a better option. – Andrey Oct 04 '12 at 03:34
1
  • 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 
}
Baba
  • 94,024
  • 28
  • 166
  • 217
0
while(!feof($file)){
   $stringData = fgets($file);//read a line on every itration

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

}
Arun Killu
  • 13,581
  • 5
  • 34
  • 61