我目前的项目需要用户定义一组存储在数据库中的数字范围。
以下字符串是可能的用户输入:
1025-1027,1030,1032-1034
我希望用php处理这个字符串,以获取可能数字的数组,包括添加数字范围的可能性,范围为n-n²
或添加单个数字,用n; n²
分开,对于这个例子来说应该是:
1025 1026 1027 1030 1032 1031 1034
将输入字符串按逗号分隔,然后查看新数组的每个元素。如果它具有范围分隔符 (-
),则将范围内的每个数字添加到数组中:
$input = '1025-1027,1030,1032-1034';
$inputArray = explode(',', $input);
$outputArray = array();
foreach($inputArray as $v) {
if(strpos($v, '-') === false) {
$outputArray[] = $v;
} else {
$minMax = explode('-',$v);
if($minMax[0]<=$minMax[1]) {
$outputArray = array_merge($outputArray, range($minMax[0], $minMax[1]));
}
}
}
print_r($outputArray);
Array
(
[0] => 1025
[1] => 1026
[2] => 1027
[3] => 1030
[4] => 1032
[5] => 1033
[6] => 1034
)
,和-都"explode",然后映射每个"exploded group",然后使用range
。创建范围后,重新合并分组:
$input = '1025-1027,1030,1032-1034';
// explode, map, explode, create range
$numbers = array_map(function($e){
$range = explode('-', $e);
return (count($range) > 1) ? range(min($range), max($range)) : $range;
}, explode(',', $input));
// re merge
$numbers = call_user_func_array('array_merge', $numbers);
print_r($numbers);