dongpao9165 2014-05-20 15:58
浏览 31

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
  • 写回答

1条回答 默认 最新

  • doujie7886 2014-05-20 16:09
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度