Bin*_*ing 5 php arrays methods numbers list
我试着在这里和谷歌上搜索这个,所以如果我错过了一些明显的东西,我道歉.我可能根本不知道这些数字格式的名称.
我要做的是从一个字符串开始,比如"1-3,5,7-9",并将它变成一个PHP数组,其中包含以下条目:1,2,3,5,7,8 ,9
我知道如何通过在逗号上使用preg_split来实现这一点,然后迭代并扩展任何标记,但我觉得必须有一个更简单/更好的方法.
编辑
我没有说清楚,但字符串需要包括SPANS!这意味着如果我的字符串是"1-9",我得到的数组应该是"1,2,3,4,5,6,7,8,9"而不是"1,9".对不起之前不清楚.
net*_*der 11
不完全确定"扩展"是什么意思.无论如何,这是我将如何做到explode和range:
$input = '1-3,5,7-9';
$output = array();
foreach (explode(',', $input) as $nums) {
if (strpos($nums, '-') !== false) {
list($from, $to) = explode('-', $nums);
$output = array_merge($output, range($from, $to));
} else {
$output[] = $nums;
}
}
Run Code Online (Sandbox Code Playgroud)
如果有更好的方法不使用eval(或PCRE e修饰符),我不知道.
为了您的娱乐,这是一个单行程(不幸的是使用eval)返回相同的结果,但......
免责声明:eval在大多数情况下不建议使用,因为它可能会产生安全风险和其他问题.我不会用它,但它仍然可行.
话虽如此,这里是:
$output = explode(',', preg_replace('/([0-9]*)-([0-9]*)/e', 'implode(",", range($1, $2));', $input));
Run Code Online (Sandbox Code Playgroud)
小智 5
上面的例程效果很好,但有一些缺点:
我更改了代码来解决这些问题:
function parsenumbers($input)
{
/*
* This routine parses a string containing sets of numbers such as:
* 3
* 1,3,5
* 2-4
* 1-5,7,15-17
* spaces are ignored
*
* routine returns a sorted array containing all the numbers
* duplicates are removed - e.g. '5,4-7' returns 4,5,6,7
*/
$input = str_replace(' ', '', $input); // strip out spaces
$output = array();
foreach (explode(',', $input) as $nums)
{
if (strpos($nums, '-') !== false)
{
list($from, $to) = explode('-', $nums);
$output = array_merge($output, range($from, $to));
}
else
{
$output[] = $nums;
}
}
$output = array_unique($output, SORT_NUMERIC); // remove duplicates
sort($output);
return $output;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1623 次 |
| 最近记录: |