php:“ sscanf”以“使用”字符串,但允许缺少参数

问题描述

|| 这是为了一个名为osCommerce的贡献 (\“自动将具有属性的多个产品从外部来源添加到购物车\”) 此现有代码使用sscanf对字符串“ \ explode \”表示 -产品ID, -productOption, -和数量:
sscanf(\'28{8}17[1]\',\'%d{%d}%d[%f]\',$productID,// 28
  $productOptionID,$optionValueID,//{8}17 <--- Product Options!!!
  $productQuantity                  //[1]
);
如果只有1个\'set \'产品选项(例如{8} 17),则效果很好。 但是需要修改此过程,以便它可以处理多个产品选项并将它们放入一个数组中,例如:
\'28{8}17{7}15{9}19[1]\' //array(8=>17,7=>15,9=>19)
OR
\'28{8}17{7}15[1]\'      //array(8=>17,7=>15)
OR
\'28{8}17[1]\'           //array(8=>17)
提前致谢。 (我是一个帕斯卡程序员)     

解决方法

也许正则表达式可能很有趣
$a = \'28{8}17{7}15{9}19[1]\';
$matches = null;
preg_match_all(\'~\\\\{[0-9]{1,3}\\\\}[0-9]{1,3}~\',$a,$matches);
得到其他东西
$id = (int) $a; // ;)
$quantity = substr($a,strrpos($a,\'[\')+ 1,-1);
根据评论稍作更新
$a = \'28{8}17{7}15{9}19[1]\';
$matches = null;
preg_match_all(\'~\\\\{([0-9]{1,3})\\\\}([0-9]{1,3})~\',$matches,PREG_SET_ORDER);
$result = array();
foreach ($matches as $entry) {
  $result[$entry[1]] = $entry[2];
}
    ,您不应尝试使用一个sscanf进行复杂的递归解析。将其粘贴成一个循环。就像是:
<?php

$str = \"28{8}17{7}15{9}19[1]\";
#$str = \"28{8}17{7}15[1]\";
#$str = \"28{8}17[1]\";
sscanf($str,\"%d%s\",$prod,$rest);
printf(\"Got prod %d\\n\",$prod);
while (sscanf($rest,\"{%d}%d%s\",$opt,$id,$rest))
 {
   printf(\"opt=%d id=%d\\n\",$id);
 }
sscanf($rest,\"[%d]\",$quantity);
printf(\"Got qty %d\\n\",$quantity);
?>
    

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...