I’m looking for a nice way to parse a string into two variables using PHP. The variables are called minage and maxage, and they should be parsed according to the examples below:
JavaScript
x
"40" -> minage=40, maxage=40
"-40" -> minage=null, maxage=40
"40-" -> minage=40, maxage=null
"40-60" -> minage=40, maxage=60
Advertisement
Answer
Try this:
JavaScript
$minrange = null;
$maxrange = null;
$parts = explode('-', $str);
switch (count($parts)) {
case 1:
$minrange = $maxrange = intval($parts[0]);
break;
case 2:
$minrange = $parts[0] == "" ? null : intval($parts[0]);
$maxrange = $parts[1] == "" ? null : intval($parts[1]);
break;
}