preg_match - 查找数据

I have a mysql database with php running a query on the table. I need to output the measurement of each order.

An example row would be "this order contains 3x6lb of flour". I need to get the 3x6lb. However, some results are also "this order contains 3 x 6lb of flour". The possible weights are lb and oz.

Output should look like:

$rownum | $measurement
1 | 3x6lb
2 | 5x10oz

This expression:

(\d+)\s*x\s*(\d+)\s*(lb|oz)

Will capture 1+ digit, followed by 0+ whitespace, followed by x, followed by 0+ whitespace, capturing 1+ digit, followed by 0+ whitespace, and finally capturing your lb or oz unit (case-insensitive with the i modifier).


PHP:

$data = array(
    array(
        'rownum' => 1,
        'measurement' => '3x6lb',
    ),
    array(
        'rownum' => 2,
        'measurement' => '5 x 10 oz',
    ),
);

foreach($data as $row) {
    if(preg_match('/(\d+)\s*x\s*(\d+)\s*(lb|oz)/i', $row['measurement'], $matches)) {
        echo $row['rownum'] . ': ' . $matches[0];

        $matches[1]; // 3
        $matches[2]; // 6
        $matches[3]; // lb
    }
}

preg_match() will return true/false if a match is found..then the entire match will be in $matches[0] with each part being in the keys 1-3.