我正在寻找一种使用PHP将字符串解析为两个变量的好方法。将包含值范围的字符串解析为最小和最大变量
"40" -> minage=40, maxage=40
"-40" -> minage=null, maxage=40
"40-" -> minage=40, maxage=null
"40-60" -> minage=40, maxage=60
我正在寻找一种使用PHP将字符串解析为两个变量的好方法。将包含值范围的字符串解析为最小和最大变量
"40" -> minage=40, maxage=40
"-40" -> minage=null, maxage=40
"40-" -> minage=40, maxage=null
"40-60" -> minage=40, maxage=60
试试这个:变量是根据下面的实例名为MINAGE和最大生存周期,他们应该被解析
$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;
}
$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]);
}
您也可以封装在一个类中的数据,说范围:
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是一些正则表达式的技巧。
这是一个好主意,但为什么要保护变量?大概你想能够访问你已经提取的数据,否则没有意义... – 2009-11-03 11:21:45
@Matthew,是的,他们可以公开,或让他们保护,并提供额外的方法在Range类(我离开出)。 – 2009-11-03 12:38:24