sscanf 为什么会忽略空格?

对下面这段代码使用$input后:

"a banana is a fruit"

$t = sscanf($input,"a %s is a %s",$child,$parent);
echo $t.",".$child.",".$parent;

会输出:


2,banana,fruit

看起来太完美了对吧!然而,如果使用$input = "a cow is an animal",我们则会得到这个输出:


2,cow,n

这是不理想的。

最理想的情况是输入$input = "a cow is an animal"它会返回1,cow,

而且我如果使用单独的格式字符串"a %s is an %s"时,它应该返回2,cow,animal

那么:为什么"a %s is a %s"第二个a之后的空格会阻止这个问题的发生?是否有方法明确表明空格必须出现在a之后才能找到正确的匹配?

希望这是有意义的问题,任何帮助都值得感激!

更新:

这是实际的代码:


$teachArray 数组(“ a% s 是 a% s” ,“ an% s 是 a% s” ,“ a% s 是 a% s” ,“ an% s 是 an% s” ,“ an% s 是 an% s”) ;

$i 0;

$t-1;

While (((t 2) & (i count ($teachArray)))){

$tscanf ($input,$teachArray [ i ] ,$child,$parent) ;

1 + + ;

}

所以它一直在循环,除非找到匹配的句子结构或者用完句子模板(存储在 $teachArray 中)。

Instead of scanf, you should use a regular expression:

$input = "a cow is an animal";
preg_match("/^an? (.+?) is an? (.+?)$/", $input, $matches);
echo (count($matches)-1) . ',' . $matches[1] . ',' . $matches[2];

I think you can still use sscanf for that, even though regexp is more flexible.

$t = sscanf($input,"%s %s is %s %s",$a1, $child, $a2, $parent);
echo $t.",".$child.",".$parent;