0
Read a text file and display all lines ending with the letter A
Plz help it shows uninitialized char value 0 What is wrong?? <?php $f=fopen('mys.txt', 'r'); while (!feof) { $n=fgets($f); $m=strrev($n); if ($m[0]=='A') echo $n; } fclose($f); ?>
5 Respostas
+ 3
Lord Pharaoh, test this out on your side and tell me how it goes, I think the problem lies on the while loop, the feof() function expected a file handle as an argument. Also you can use substr() function with negative start index to read in from behind.
<?php
$f=fopen('mys.txt', 'r');
while (!feof($f))// while (!feof)
{
$n=fgets($f);
//$m=strrev($n);// no need to reverse
if(substr($n, -1) == 'A')// ($m[0]=='A')
echo $n;
}
fclose($f);
?>
Hth, cmiiw
+ 2
Looks like the problem is that fgets() function reads the line without removing the new line character off the string buffer, can you change the code like this and try again?
if(substr($n, -2) == 'A')
If you write the mys.txt file with Notepad or something there's a possibility that line break character was '\r\n' instead of just '\n'. In that case, probably we'll have to do:
if(substr($n, -3) == 'A')
But if you write the file with code, using '\n' for line breaks -2 index for substr() function might do the work.
+ 1
not working bro shows no output
cannot understand this time there is no error message just blank screen
+ 1
Okay bro ... so can you show some example of the file content? maybe I can try to test in Playground. Also tell me, are you running this in Playground or your computer/laptop?
P.S. It's kinda hard to tell with no error message ...
+ 1
so basically my text file has 5 words
INDIA
CHINA
GERMANY
SPAIN
AMERICA
now i am running this on my laptop
wamp server
php version 7.0.4
using sublime text