【问题标题】:combination regex and php still not work组合正则表达式和 php 仍然不起作用
【发布时间】:2010-08-18 03:03:40
【问题描述】:

大家好。我是这个问题的新手。我在表格结果中有这些数据:

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 评论。

标签: php mysql regex


【解决方案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 值。或许你可以详细说明一下。

【讨论】:

  • 看起来 A/B/C 列只是代表“代码”数据库表内容的位域。如果代码 = A,则 A = 1,B = 0,C = 0 等......不知道 S 可能是什么,除了(显然来自给定样本)一个零字段
  • @Marc B:你可以在我的链接问题中看到。
猜你喜欢
  • 1970-01-01
  • 2013-06-19
  • 2014-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多