【问题标题】:PHP parse field and calculate difference [closed]PHP解析字段并计算差异[关闭]
【发布时间】:2014-06-06 14:21:36
【问题描述】:

谁能提供一种方法来解析具有如下格式的字段并获取冒号之间的两个值之间的差异。

bot1:11874-12227:top

例如,结果字段将等于 12227-11874 = 353。

我认为类似于按分隔符扫描,然后评估差异的负数。

【问题讨论】:

  • 你尝试写的代码在哪里?
  • 这个正则表达式就够了/:(\d+)-(\d+):/

标签: php evaluate


【解决方案1】:
$string = "bot1:11874-12227:top";
$parts = explode(":", $string);
$numbers = explode("-", $parts[1]);
$difference = (($numbers[1] - $numbers[0]) > 0) ? $numbers[1] - $numbers[0] : $numbers[0] - $numbers[1];

echo $difference;

【讨论】:

  • @gnagy。最后一部分 $difference 看起来相当复杂。让我盯着它看几分钟,然后搜索如何解释。再次感谢!
  • 最后一部分基本上是一个 if 语句,如果你的第二个数字大于第一个,则返回它们的差值(第二个 - 第一个),否则返回第一个 - 第二个。如果你 100% 确定第二个数字总是更大,你可以写 $difference = $numbers[1] - $numbers[0]
  • 最后一部分可以简化为$difference = abs($numbers[1] - $numbers[0]);
【解决方案2】:

只需使用带有preg_match 的正则表达式即可:

$string = 'bot1:11874-12227:top';

preg_match("#[A-Za-z]+[0-9]?:([0-9]+)([-|+|*|//])([0-9]+):[A-Za-z]+#", $string, $matches);

echo '<pre>';
print_r($matches);
echo '</pre>';

结果是:

Array
(
    [0] => bot1:11874-12227:top
    [1] => 11874
    [2] => -
    [3] => 12227
)

然后只需执行以下数学运算:

echo abs($matches[1] - $matches[3]);

现在,请注意$matches[2] 如何匹配数学运算符?那么,为什么不利用create_function 执行以下操作:

$string_to_math_results = create_function("", "return ($matches[1] $matches[2] $matches[3]);" );

echo abs($string_to_math_results());

所以像这样把它们放在一起。现在您不仅可以解析字符串中的值,还可以根据字符串中的值进行基本计算:

$string = 'bot1:11874-12227:top';

preg_match("#[A-Za-z]+[0-9]?:([0-9]+)([-|+|*|//])([0-9]+):[A-Za-z]+#", $string, $matches);

$string_to_math_results = create_function("", "return ($matches[1] - $matches[3]);" );

echo abs($string_to_math_results());

【讨论】:

  • 这就够了/:(\d+)-(\d+):/
  • @FerozAkbar “这就够了” 对我来说不够好。看看我最新的编辑。我认为所有的基础都涵盖了。
  • 随你喜欢的朋友:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-05
  • 1970-01-01
  • 2016-05-07
  • 2010-10-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多