parsing - php sscanf doesnt parse string properly

703

I develop ADIF parser and parsing process comes to the point where I use sscanf() php function The strind that I parse is as following: "QSO_DATE:8:D>20070909" and I need to draw info from here as following: "QSO_DATE", "8", "20070909" so I use code:

sscanf("QSO_DATE:8:D>20070909", "%s:%d:D>%d")

But returning array looks like this:

    Array
(
    [0] => QSO_DATE:8:D>20070909
    [1] => 
    [2] => 
)

What is wrong? maybe there is more efficient way to parse bunch of records like these:

<CALL:7>EM200FT<QSO_DATE:8:D>20140324<TIME_ON:4>1657<BAND:3>12M<MODE:5>PSK63<RST_SENT:3>599<RST_RCVD:0><QSL_SENT:1>Y<QSL_SENT_VIA:1>E<APP_EQSL_AG:1>Y<GRIDSQUARE:6>KN45kj<EOR>
<CALL:5>9V1SV<QSO_DATE:8:D>20140328<TIME_ON:4>1019<BAND:3>10M<MODE:4>JT65<RST_SENT:6>VK4CMV<RST_RCVD:0><QSL_SENT:1>Y<QSL_SENT_VIA:1>E<QSLMSG:54>Thank you and I confirm your SWL report, 73's de Siva.<APP_EQSL_AG:1>Y<GRIDSQUARE:6>OJ11ui<EOR>
<CALL:5>RA6DQ<QSO_DATE:8:D>20140328<TIME_ON:4>1019<BAND:3>10M<MODE:4>JT65<RST_SENT:3>599<RST_RCVD:0><QSL_SENT:1>Y<QSL_SENT_VIA:1>E<QSLMSG:3>73!<APP_EQSL_AG:1>Y<GRIDSQUARE:6>KN85nf<EOR>
599

Answer

Solution:

%s means any characters, including colons, digits, chevrons, etc, except whitespace characters) and sscanf uses a greedy grab.... using more precise alternatives like%[A-Z_] or%[^:] might serve you better that%s

$result = sscanf("QSO_DATE:8:D>20070909", "%[^:]:%d:D>%d");
var_dump($result);

Which uses%[^:] to scan for any character other than a:

People are also looking for solutions to the problem: php - Laravel 4: how show query results in footer

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.