开发者

What is the regex of extracting single letter or two letters?

There are two string

$str = "Calcium Plus Non Fat Milk Powder 1.8kg";
$str2 = "Super Dry Diapers L 54pcs";

I use

preg_match('/(?P&l开发者_运维百科t;name>.*) (?P<total_weight>\b[0-9]*\.?[0-9]+)(?P<total_weight_unit>.*)/', $str, $m);

to extract $str and $str2 is similar way. However I want to extract them such that I know it is weight(i.e. kg, g, etc) or it is portion(i.e. pcs, cans). How can I do this??


If you want to capture number and unit for pieces and weight at the same time, try this:

$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


maybe

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


I would suggest ([0-9]+)([^ |^<]+) or ([0-9]+)(.{2,3})


I think you are looking for this code:

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

I've added parentheses which bounds fractional part. Question mark (?) means zero or one match.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜