假设我在格式中有一个变量$peopleSize(我已经从UI元素中提取了信息):
xxx-yyyy people
例如,如jquery范围UI中所示:
http://jsfiddle.net/methuselah/SLvtx/1/
如何使用PHP去掉"-"answers"people",将两个min和max作为两个独立的变量?
一个简单的方法是像一样使用sscanf()
sscanf("3-456 people", "%d-%d", $min, $max);
// $min contains 3, $max contains 456
实现此操作的多种方法之一:在'-'
和' '
上拆分字符串。
$peopleSize = 'xxx-yyyy people';
$parts = preg_split('-| ', $peopleSize);
$min = $parts[0];
$max = $parts[1];
list($min, $max) = explode('-', strtok($peopleSize, ' '));
<?php
$str = "300-1000 people";
preg_match("|('d+)-('d+)|", $str, $matches);
//$matches[0] will hold the whole min-max string.
$min = $matches[1]; //First matched group, first set of numbers.
$max = $matches[2]; //Second matched group, second set of numbers.
echo "$min to $max";