Php fgets() and trim()

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
jewelthief
Forum Newbie
Posts: 13
Joined: Sat Aug 29, 2009 1:46 am

Php fgets() and trim()

Post 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.
Last edited by jewelthief on Thu Sep 03, 2009 12:44 pm, edited 1 time in total.
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: Php fgets() and trim()

Post by John Cartwright »

Post code
jewelthief
Forum Newbie
Posts: 13
Joined: Sat Aug 29, 2009 1:46 am

Re: Php fgets() and trim()

Post 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.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Php fgets() and trim()

Post by requinix »

Code: Select all

rtrim($line);
rtrim will return the trimmed string, not save it back into $line.
jewelthief
Forum Newbie
Posts: 13
Joined: Sat Aug 29, 2009 1:46 am

Re: Php fgets() and trim()

Post by jewelthief »

oops. such a simple mistake. Thanks anyway
Post Reply