将包含值范围的字符串解析为最小和最大变量

时间:2009-11-03 10:06:03

标签: php

我正在寻找一种使用PHP将字符串解析为两个变量的好方法。变量称为minage和maxage,它们应根据以下示例进行解析:

"40" -> minage=40, maxage=40
"-40" -> minage=null, maxage=40
"40-" -> minage=40, maxage=null
"40-60" -> minage=40, maxage=60

3 个答案:

答案 0 :(得分:4)

试试这个:

$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;
}

答案 1 :(得分:2)

您也可以将数据封装在类中,比如Range:

class Range {

  protected $min;
  protected $max;

  public function __construct($str) {
    if(preg_match('/^\d+$/', $str)) {
      $this->min = (int)$str;
      $this->max = (int)$str;
    } else {
      preg_match('/^(\d*)-(\d*)$/', $str, $matches);
      $this->min = $matches[1] ? (int)$matches[1] : null;
      $this->max = $matches[2] ? (int)$matches[2] : null;
    }
  }

  // more functions here like contains($value) and/or min() and max()

  public function __toString() {
    return 'min=' . $this->min . ', max=' . $this->max;
  }
}

$tests = array('40', '-40', '40-', '40-60');
foreach($tests as $t) {
  echo new Range($t) . "\n";
}

产生:

min=40, max=40
min=, max=40
min=40, max=
min=40, max=60

当然,您可以使用一些“普通”字符串函数替换preg_调用,但我唯一知道的PHP是一些正则表达式技巧。

答案 2 :(得分:0)

$parts = explode("-", $str);
$minage = NULL;
$maxage = NULL;
if (count($parts) == 1) {
  $minage = intval($parts[0]);
  $maxage = $minage;
}
else if ((count($parts) >= 2) && is_numeric($parts[0]) && is_numeric($parts[1])) {
  $minage = intval($parts[0]);
  $maxage = intval($parts[1]);
}