在PHP中使用sscanf的错误结果


Wrong Results by Using sscanf in PHP

这是我正在运行的代码结果是错误的!

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

但结果我得到

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

结果应该是:

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

我在做什么?我该怎么解决?

您的格式参数中有太多逗号;传入字符串中只有一个逗号。sscanf()中的占位符总是贪婪的。%s占位符匹配连续的非空白字符。您可以通过使用包含逗号的否定字符类来排除占位符使用的逗号。

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

给你

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

这是关于逗号的,将其从格式中删除:

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

这个应该返回:

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

如果您不想在结果中使用逗号,可以使用str_replace

将其从第一个数组中删除

如果你不想要逗号,试试这个:

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

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

试试这个:

$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);