Page 1 of 1

Php fgets() and trim()

Posted: Thu Sep 03, 2009 12:38 pm
by jewelthief
Hello!
I am reading from a file called abc.txt. It has 3 lines containing of one word each.

when I loop through these lines with fgets() function and check the length of the strings returned, I get the length 2 more than the actual length is. I have checked the ascii codes of those last two characters which is 10 i.e. new line so I tried to trim the last two characters by trim() fucntion but to no avail. It doesnt trim them at all.

I must add that it reads the last line perfectly fine which obviously doesnt have line feed.

1) why fgets() not returning the normal string with not line feeds?
2) why doesnt trim() trim those extra characters?



Any suggestions why this is happening? Help would be appreciated.

Re: Php fgets() and trim()

Posted: Thu Sep 03, 2009 12:41 pm
by John Cartwright
Post code

Re: Php fgets() and trim()

Posted: Thu Sep 03, 2009 12:47 pm
by jewelthief

Code: Select all

<?php 
            $str= $_POST["field1"];
            $file = fopen("abc.txt","r");
            $flag = 0;
            while( !feof($code_file) )
            {
                $line = fgets($file);
                rtrim($line);
                if( strcmp( $str, $line ) == 0)
                {
                    $flag = 1;
                    echo "Successful";
                    break;
                }   
             }
             if( $flag == 0 )
                echo "Invalid";
            fclose($file);
    ?>

I must add that it reads the last line perfectly fine which obviously doesnt have line feed.

Re: Php fgets() and trim()

Posted: Thu Sep 03, 2009 2:33 pm
by requinix

Code: Select all

rtrim($line);
rtrim will return the trimmed string, not save it back into $line.

Re: Php fgets() and trim()

Posted: Fri Sep 04, 2009 2:36 am
by jewelthief
oops. such a simple mistake. Thanks anyway