Wuhtzu Posted December 5, 2006 Share Posted December 5, 2006 HeyI 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.txtThe 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 adviceWuhtzuIs 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 More sharing options...
genericnumber1 Posted December 5, 2006 Share Posted December 5, 2006 [code=php:0]$wordlist_danish[]=$word;[/code]becomes....[code=php:0]$wordlist_danish[]=trim($word);[/code]pretty 'nuf? ;)though it isn't how I'd write the script, I'll keep my code to myself :D Link to comment https://forums.phpfreaks.com/topic/29497-fgets-is-adding-a-space-or-line-break/#findComment-135365 Share on other sites More sharing options...
Wuhtzu Posted December 5, 2006 Author Share Posted December 5, 2006 "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. Link to comment https://forums.phpfreaks.com/topic/29497-fgets-is-adding-a-space-or-line-break/#findComment-135563 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.