组合正则表达式和PHP仍然无法正常工作

时间:2010-08-18 03:03:40

标签: php mysql regex

嘿all.i是这个问题的新手。我在表结果中有这个数据:

item              range_code                   class
red               123x0001-123x0500             A
blue              123x0021-123x0100             //if null read zero
green             123x0001-123x0300             b

我想要的结果如下:

item             qty           S           A         B          C
 red             500           0           1         0          0
 blue            80            0           0         0          0
 green           300           0           0         1          0

我尝试过这段代码,但仍无效:

$sql= 'SELECT item, range_code as qty, class FROM result GROUP BY item, qty';
$result=mysql_query($sql);
while ($row=mysql_fetch_assoc($result)){
         preg_match_all('/\d+(?=-|$)/g',$row['qty'],$matches);
         echo intval($matches[0][1])-intval($matches[0][0])+1;
         }

我仍然对这个问题感到困惑。 请帮忙..

1 个答案:

答案 0 :(得分:1)

不确定这是否正在执行您想要的操作...如果没有,请说明是否存在任何不匹配的边缘情况,但根据您的示例,这应该可行。

<?php

$code = "123x0001-123x0500";
preg_match("/^\d+x(\d+)-\d+x(\d+)$/", $code, $matches);
echo intval($matches[2]) - intval($matches[1]) + 1;

?>

输出:

500

<?php

$codes = array("123x0001-123x0500",  "123x0021-123x0100", "123x0001-123x0300");

function getDiff($range) {
    preg_match("/^\d+x(\d+)-\d+x(\d+)$/", $range, $matches);
    return intval($matches[2]) - intval($matches[1]) + 1;
}

foreach ($codes as $code) {
    echo getDiff($code) . "\n";
}

?>

输出

500
80
300

不确定如何计算S,A,B,C值。也许你可以详细说明。