开发者

Parse string containing range of values to min and max variables v2

I need to parse a string to two variables according to the following rules, and I'm looking for the best way to achieve this in PHP:

"40.3" -> minval=40.3, maxval=40.3
"-40.3" -> minval=-40.3, maxval=-40.3
"40.3-60.76" -> minval=40.3, maxval=60.76
"-40.3-60.76" -> minval=-40.3, maxval=60.76
"-60.76--40.3" -> minval=-60.76, maxval=-40.3

Unfortunately I have to use minus both for negative values, as well as range separator.

This is pretty similar to my开发者_开发百科 previous question:

Parse string containing range of values to min and max variables

(I already once posted this second question but noticed that I had messed the table. Hopefully it's fine now.)


As much as I try to avoid regular expressions, I would use one in this case. I think this should match all your strings:

preg_match('/^(?P<min>-?\d+(\.\d+)?)(-(?P<max>-?\d+(\.\d+)?))?/', $string, $matches);
$min = $matches['min'];
if (isset($matches['max'])) {
     $max = $matches['max'];
}

(The length of the regular expression is a good reason to avoid them in day-to-day coding)


When encountering such a problem, you can try expressing it in some kind of Backus-Naur form:

Range := Number | Number "-" Number
Number := Sign Digits
Sign := "" | "-"
Digits := Digit* | Digit* "."  Digit*

And create a regular expression from that.


if you don't want to use regular expressions, this function will do it:

function parse_range($range) {
    list($from, $to) = explode('-', substr($range, 1), 2);
    $from = $range[0] . $from;
    if (!$to and $to !== '0') {
        $to = $from;
    }
    return array($from * 1, $to * 1);
}


$test = array(
  "40.3",
  "-544",
  "40.3-60",
   "-40.1234-60.76",
  "-60.76--40.3",

);

$num = "(-?\d+(?:\.\d+)?)";
$re = "~^$num-?$num?$~";
foreach($test as $test) {
    if(preg_match($re, $test, $m)){
       if(!isset($m[2])) $m[2] = $m[1];
       echo "from $m[1] to $m[2]\n";
    }
}


This worked quite well in a test:

<?php
preg_match("/^(\-{0,1}[0-9\.])\-{0,1}(\-{0,1}[0-9\.]*)\$/", "-1-2", $matches);
$min = $matches[1];
$max = $matches[2] ? $matches[2] : $min;
?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜