2011-10-19 21 views
5

我試着在Google和Google上搜索這個,所以如果我錯過了某些明顯的東西,我很抱歉。有可能我根本不知道這些數字格式的名稱。PHP:有沒有簡單的方法來解析數組列表(如字符串,如「1-3,5,7-9」)到數組中?

我想要做的是以字符串開頭,如「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」。對不起,以前不清楚。

+1

你看着爆炸? http://php.net/manual/en/function.explode.php –

+5

我很高興大家在這裏仔細閱讀這個問題... – animuson

+0

我編輯了帖子......我的問題是跨度,像「1-5 「需要導致」1,2,3,4,5「不只是」1,5「 – Bing

回答

11

不完全確定你的意思是「擴大」。總之,這裏的我如何與exploderange做到這一點:

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

如果有不使用eval(或PCRE e修改),我不知道有什麼更好的辦法。

這裏,爲您的娛樂,一個班輪(即不幸的是使用eval)返回相同的結果,但是......

免責聲明:是不是在大多數情況下,因爲建議不要使用eval它可能會造成安全風險和其他問題。 我不會用它但它仍然可行。

雖這麼說,那就是:

$output = explode(',', preg_replace('/([0-9]*)-([0-9]*)/e', 'implode(",", range($1, $2));', $input)); 
+0

這工作,謝謝! – Bing

1

我不知道內置的方式簡單的,因爲它不是東西是大家常見的,我懷疑有內置的東西。

的方式你描述像一個合理的做法聲音。只需對字符串進行一次迭代就可以完成它,但除非它是已知的性能問題,否則我不打擾它。

+0

+1我絕對忽略了跨越並將它們視爲分隔符。 – Josh

1
$str = '1-3,5,7-9'; 
$arr = explode(',', $str); 
$result = array(); 
foreach($arr as $a){ 
    $x = explode('-', $a); 
    if(count($x) === 2){ 
    $x = range($x[0], $x[1]); 
    } 
    $result = array_merge($result, $x); 
} 
print_r($result); 

不知道如何高效,這是,但它能夠完成任務。

0

走開做到這一點,我回來看到2個答案。 :(

<?php 
function arrex($s){ 
    $arr = explode("-", $s); 
    $v=$arr[0] + 1; 
    $val = array(); 
      while($v!=$arr[1]){ 
       $val[$v] = $v; 
        $v++; 
      } 
    array_unshift($val, $arr[0]); 
    array_push($val, $arr[1]); 
return $val; 
} 
$s = "1-9"; 
print_r(arrex($s)); 
?> 

輸出

Array 
(
    [0] => 1 
    [1] => 2 
    [2] => 3 
    [3] => 4 
    [4] => 5 
    [5] => 6 
    [6] => 7 
    [7] => 8 
    [8] => 9 
) 
1

上面的常規工作得很好,但具有一些缺點:

  1. 空間字符串中打亂了常規
  2. 重複不例如除去5,4-7給出5,4,5,6,7
  3. 這些數字沒有排序。

我已經改變了代碼來理清這些問題:

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; 
} 
相關問題