doupoji3856 2012-07-02 10:55 采纳率: 100%
浏览 1083
已采纳

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 中)。

  • 写回答

2条回答 默认 最新

  • dscbxou1900343 2012-07-02 12:39
    关注

    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];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 关于#python#的问题:自动化测试