I have a text file that I'm reading line by line. When I get to the line that's a string (six words long) I want to read it and assign it to the variable $str, so I do this:
fscanf($handle, "%s", $str);
//The line is "one two three four"
echo $str ; // prints out "one"
However, it only saves the first word of the string, due to the spaces after each word. How do I capture the whole thing?
It's old question, but for googlers:
To read a whole line with fscanf(), use "%[^\n]". In fscanf(), $[^characters] means to match any sequence of characters that isn't in the set between the brackes (it's similar to [^characters]* in a regular expression). So this matches any sequence of characters other than newline. See http://php.net/manual/en/function.sscanf.php#56076
from PHP fscanf vs fgets
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With