2011-10-14 64 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 
相關問題