Jump to content

fgets() is adding a space or line break!?!


Wuhtzu

Recommended Posts

Hey

I have this little piece of code which reads a file line by line and save each line (word) in an array.

[code]
$filename="wordlist_danish.txt";
$fp=fopen($filename,"r");

while(!feof($fp)){
$word=fgets($fp,1024));
$wordlist_danish[]=$word;
}
[/code]

My problem is that all words ends up with a space (or maybe a line break) at the end. For example the word "angreb" gets stored in the array as "angreb ". This becomes a problem when it need to compare the words to other strings to see if they match...

The text: http://wuhtzu.dk/gorandom/wordlist_danish.txt
The script: http://wuhtzu.dk/gorandom/test.php

[b]test.php[/b]
[code]
<?
$filename="wordlist_danish.txt";

$start_time=microtime();
$fp=fopen($filename,"r");
while(!feof($fp)){
$word=fgets($fp,1024);
$wordlist_danish[]=$word;
}
$finish_time=microtime();

$exe_time=$finish_time-$start_time;

//echo "Execution time: ".$exe_time;

echo "word(length)<br>\n";
$i=0;
while($i < count($wordlist_danish)){
$word=$wordlist_danish[$i];
$length=strlen($word);
echo $word."(".$length.")<br>";
$i++;
}

?>
[/code]

Notice the length of the word and the length of the string does not match and notice the source of the output of test.php - every "word(length)<br>" is nicely placed on seperate lines even though i didnt echo any "\n".... So I maybe think it is a line break at the end of each word...

Is this supposed to happen and is there any "pretty" way of fixing it?


Thanks in advice
Wuhtzu

Is there something wrong with my code?
Link to comment
https://forums.phpfreaks.com/topic/29497-fgets-is-adding-a-space-or-line-break/
Share on other sites

"though it isn't how I'd write the script, I'll keep my code to myself" are you criticizing my code :P The test.php is awfull so don't look at that -> but how would you get all the words from wordlist_danish.txt into an array any better than:

$filename="wordlist_danish.txt";
$fp=fopen($filename,"r");

while(!feof($fp)){
$word=fgets($fp,1024));
$wordlist_danish[]=$word;
}


--------------------------

Btw thanks for the trim() workaround - it worked.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.