简体   繁体   中英

sscanf and white-space problems

I'm really getting mad for a problem that I hope you can help me to fix.

Scenery.

A php file reads some data in a text file and populate a mysql database. For this purpose I used the function "sscanf" and everything work very well...but not always! Due to a little format difference of some textual data files, fields in the database are filled wrong.

Here is an example:

This is a generic line of the data file .txt:

...
<name:4>John <country:3>USA <age:2>20
...

To read data in the file and populate the MyQSL database I use the function sscanf followed by specific parameters, as shown in the following examples:

 $values = sscanf ($s, "<name:%d>%s ", $length,$personal_data['name']);
 $values = sscanf ($s, "<country:%d>%s ", $length,$personal_data['country']);
 $values = sscanf ($s, "<age:%d>%s ", $length,$personal_data['age']);

These parameters are OK and the MyQSL database is populated correctly; each field has its data. NAME -> "John" - COUNTRY -> "USA" - AGE "20"

Unfortunately text files containing my data are a little bit different, even though use the same format. Here is another example:

 <name:4>John<country:3>USA<age:2>20

In this case, the sscanf function with identical parameters used before, works wrong. All fields in the database have wrong data. This is because there is no a white-space at the end of each field in the source file (.txt) The database will be populated in this way NAME -> "John "ry:3>USA" - AGE "

So i must modify sscanf parameters as follow:

 $values = sscanf ($s, "<name:%d>%s<", $length,$personal_data['name']);
 $values = sscanf ($s, "<country:%d>%s<", $length,$personal_data['country']);
 $values = sscanf ($s, "<age:%d>%s<", $length,$personal_data['age']);

and everything is OK again.

The problem is the white-space. In some .txt files is present after each field and in other files not. You can notice differences after the %s parameter (followed by a white-space in one case and by < in other).

How can i fix the problem? Is there a way to tell sscanf that in the textual source file each field ends with a white-space or < ?? Any suggestion? Idea?

Thanks in advance, Mattew

I don't have currently PHP installed so i can't test this answer, but you can split that string using a regular expression with preg_split() .

Example:

$str = '<name:4>John<country:3>USA<age:2>20';
$values = preg_split('/<[a-z]+:\d>/', $str);

$data will be an array with values of each field.

PHP - preg_split()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM