Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read entire line (string) using fscanf?

Tags:

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?

like image 664
a53-416 Avatar asked Apr 03 '16 18:04

a53-416


1 Answers

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

like image 191
Serge P Avatar answered Sep 28 '22 19:09

Serge P