Wrong Results by Using sscanf in PHP

2019-08-27 21:17发布

问题:

Here is the Code i'm running Results are wrong as they supposed to be!

$results = sscanf("Sept 30th, 2014 ", "%s , %s, %d");
print_r($results);

But Results i'm Getting

(
   [0] => Sept
   [1] => 
   [2] => 
)

Results supposed to be :

(
  [0] => Sept
  [1] => 30th
  [2] => 2014
)

What's Wrong am i doing ? how can i fix that ?

回答1:

without str_replace for commas, you can do it like

$results = sscanf("Sept 30th, 2014 ", "%s %[^','], %d");
print_r($results);

gives you

Array ( [0] => Sept [1] => 30th [2] => 2014 )

you can omit comma in the pattern itself.



回答2:

It's about the comma, remove it from the format:

$results = sscanf("Sept 30th, 2014 ", "%s %s %d");

this should return:

Array
(
    [0] => Sept
    [1] => 30th,
    [2] => 2014
)

If you don't want the comma in result, you can remove it from the first array with str_replace or something



回答3:

If you don't want the comma try this:

$results = sscanf("Sept 30th, 2014 ", "%s %s %d");
$results = str_replace(',', '',$results);
print_r($results);

output: Array ( [0] => Sept [1] => 30th [2] => 2014 )



回答4:

try this:

$results = sscanf(" Sept 30th, 2014 ", "%s  %s %d");
$results[1]=str_replace(',','',$results[1]);// this can be done for entire array also.
print_r($results);


标签: php scanf