有两个字符串
$str = "Calcium Plus Non Fat Milk Powder 1.8kg";
$str2 = "Super Dry Diapers L 54pcs";
我用
preg_match('/(?P<name>.*) (?P<total_weight>\b[0-9]*\.?[0-9]+)(?P<total_weight_unit>.*)/', $str, $m);
以类似的方式提取$ str和$ str2。 但是,我想提取它们,以便我知道它是重量(即千克,克等)或它是部分(即个人,罐头)。 我怎么能这样做?
答案 0 :(得分:1)
如果您想同时捕获number
和unit
的碎片和重量,请尝试以下操作:
$number_pattern="(\d+(?:\.\d+))"; #a sequence of digit with optional fractional part
$weight_unit_pattern="(k?g|oz)"; # kg, g or oz (add any other measure with '|measure'
$number_of_pieces_pattern="(\d+)\s*(pcs)"; # capture the number of pieces
$pattern="/(?:$number_pattern\s*$weight_unit_pattern)|(?:$number_pattern\s*$number_of_pieces_pattern)/";
preg_match_all($pattern,$str1,$result);
#now you should have a number and a unit
答案 1 :(得分:0)
也许
$str = "Calcium Plus Non Fat Milk Powder 1.8kg";
$str2 = "Super Dry Diapers L 54pcs";
$pat = '/([0-9.]+).+/';
preg_match_all($pat, $str2, $result);
print_r($result);
答案 2 :(得分:0)
我建议([0-9] +)([^ | ^&lt;] +)或([0-9] +)(。{2,3})
答案 3 :(得分:0)
我认为您正在寻找此代码:
preg_match('/(?P<name>.*) (?P<total_weight>\b[0-9]*(\.?[0-9]+)?)(?P<total_weight_unit>.*)/', $str, $m);
我添加了括号中的小数部分。问号(?)表示零或一个匹配。