【发布时间】:2014-06-06 14:21:36
【问题描述】:
谁能提供一种方法来解析具有如下格式的字段并获取冒号之间的两个值之间的差异。
bot1:11874-12227:top
例如,结果字段将等于 12227-11874 = 353。
我认为类似于按分隔符扫描,然后评估差异的负数。
【问题讨论】:
-
你尝试写的代码在哪里?
-
这个正则表达式就够了
/:(\d+)-(\d+):/
谁能提供一种方法来解析具有如下格式的字段并获取冒号之间的两个值之间的差异。
bot1:11874-12227:top
例如,结果字段将等于 12227-11874 = 353。
我认为类似于按分隔符扫描,然后评估差异的负数。
【问题讨论】:
/:(\d+)-(\d+):/
$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;
【讨论】:
$difference = abs($numbers[1] - $numbers[0]);
只需使用带有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+):/