Reputation: 859
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
Reputation: 95101
trim
to remove all white spacesfile
can read all the content as arrayarray_map
to apply trim to all array contentin_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
Reputation: 14233
while(!feof($file)){
$stringData = fgets($file);//read a line on every itration
if (strpos($stringData , "Bill") !== false) {
//do somting
}
}
Upvotes: 0
Reputation: 14233
$var = "Bill";
$input = "Kate
Johnny
Bill
Kermit";
$output = str_replace($var ."\r\n", "", $input ."\r\n");
Upvotes: 2