2011-10-14 62 views
0

有两个字符串提取单个字母或两个字母的正则表达式是什么?

$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的是同样的方式。 但是我想提取它们,以便我知道它是重量(即kg,g等),或者它是部分(即pcs,cans)。 我该怎么做?

回答

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

我建议([0-9] +)|({2,3})([^^<] +)或([0-9] +)

0

我认为你正在寻找这样的代码:

preg_match('/(?P<name>.*) (?P<total_weight>\b[0-9]*(\.?[0-9]+)?)(?P<total_weight_unit>.*)/', $str, $m); 

我加括号其界定小数部分。问号(?)表示零次或一次匹配。

1

如果你想捕捉numberunit的同时件数和重量,试试这个:

$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 
相关问题