PHP简化了范围创建

时间:2013-12-22 06:16:03

标签: php range simplify

我写了这段代码来生成数字范围。

有人可以帮我简化这段代码吗?我认为它可以用更简单,更清洁的方式完成,但不知道怎么做?

$variant_ids = 'AB0000001, AB0000002, AB0000003 - AB0000010, AB0000011 - AB0000020, AB0000021, AB0000022';
$delimiter = ',';
$range_delimiter = '-';

$variant_ids = array_filter(array_map('trim', explode($delimiter, $variant_ids)), 'strlen');

if (is_array($variant_ids)) {
    foreach ($variant_ids as &$variant_id) {
        if (strpos($variant_id, $range_delimiter) !== FALSE && substr_count($variant_id, $range_delimiter) == 1) {
            $variant_range_id = array_map('trim', explode($range_delimiter, $variant_id));
            $variant_id = array();
            for ($i = $variant_range_id[0]; $i <= $variant_range_id[1]; $i++) {
                $variant_id[] = $i;
            }
            $variant_id = implode($delimiter, $variant_id);
        }
    }
}

$variant_ids = implode($delimiter, $variant_ids);

echo '<pre>'; print_r($variant_ids); echo '</pre>';

1 个答案:

答案 0 :(得分:1)

有趣的概念,我相信PHP内置的range函数可以很好地处理。使用rangestr_pad&amp;更新您的逻辑以将该概念用作数组。一些正则表达式杂耍。不完美,但根据您原来的代码需求,如果我自己这样说,它似乎是一个不错的选择。

// Set the basics
$raw_variant_ids = 'AB0000001, AB0000002, AB0000003 - AB0000010, AB0000011 - AB0000020, AB0000021, AB0000022';
$delimiter = ',';
$range_delimiter = '-';
$variant_ids = array();

// Explode the $raw_variant_ids to generate an array.
$range_array = explode($delimiter, $raw_variant_ids);

// Roll through the $range_array.
foreach ($range_array as $range_value) {

  // Split the range value.
  $range_split = explode($range_delimiter, $range_value);

  // If the range split has two items, generate a range. Or else, just as a straight id.
  if (count($range_split) == 2) {

    // Get the numbers for the start & end of the range.
    $range_number_start = trim(preg_replace('/[a-zA-Z]/is', '', $range_split[0]));
    $range_number_end = trim(preg_replace('/[a-zA-Z]/is', '', $range_split[1]));

    // Get the letters for the start of the range. 
    $alpha_prefix = trim(preg_replace('/[0-9]/is', '', $range_split[0]));

    // Get the length of the numbers based on the start number.
    $id_length = strlen($range_number_start);

    // Now use 'range()' to generate a range.
    $range_span_array = range($range_number_start, $range_number_end);

    // Roll through the $range_span_array.
    foreach ($range_span_array as $range_span_array_value) {
      $variant_ids[] = $alpha_prefix . str_pad($range_span_array_value, $id_length, 0, STR_PAD_LEFT);
    }
  }
  else {
    foreach ($range_split as $range_split_value) {
      $variant_ids[] = trim($range_split_value);
    }
  }

}

echo '<pre>';
print_r($variant_ids);
echo '</pre>';