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!

5
  • strpos() can return a 0 if the position is the first-character of the line, so your if statement fails. Try if (strpos($fileContents, "Bill") !== false) { instead. Commented Oct 4, 2012 at 3:13
  • Do you mean you want to delete the line of Bill ? Commented Oct 4, 2012 at 3:13
  • its a new line char whay u want to remove? Commented Oct 4, 2012 at 3:15
  • Yes, I would like to delete the line of <code>Bill</code>. Commented Oct 4, 2012 at 3:16
  • related: stackoverflow.com/questions/2267762/… Commented Mar 7, 2013 at 17:15

3 Answers 3

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

$output = str_replace($var ."\r\n", "", $input ."\r\n");
Sign up to request clarification or add additional context in comments.

3 Comments

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!
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.
I'll replace it with trim, just in case. It seems like a better option.
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 
}

Comments

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

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

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.