生成两个字母数字值之间的范围


Generate a range between two alphanumeric values

我有一组数据,其中每个项都有一个不同类型的"range from"answers"range to"字符串。例如,第一个项目可能有3001A->4000A,下一个项目可能是DE25500->DE27419,依此类推(有几种不同的模式,但通常由静态部分和范围部分组成(似乎通常任何字母都是静态的,数字可以是静态的也可以不是静态的)。

PHP中是否有现成的函数可以处理生成范围中的中间值?或者,如果没有任何关于如何构建的提示?

我不是PHP专家,但你不能为此使用for循环吗。

您需要提取值中表示范围的部分,然后开始从最低到最高的循环。

$min = (int) substr("DE25500", 2)
$max = (int) substr("DE27419", 2)
for ($x = $min; $x <= $max; $x++) {
    // logic in here
}

我建议您首先找到所有的模式,然后编写知道如何将数字部分从普通部分细分的函数。然后,要使用PHP中的范围,可以使用http://php.net/range

最终找到了一个函数来完成。。。

function generateRange($startString, $endString, $step = 1)
{
    if (strlen($startString) !== strlen($endString)) {
        throw new LogicException('Strings must be equal in length');
    }
    // Get position of first character difference
    $position = mb_strlen(mb_strcut($startString, 0, strspn($startString ^ $endString, "'0")));
    if (!is_numeric($startString[$position]) || !is_numeric($endString[$position])) {
        throw new LogicException('The first character difference is not numeric');
    }
    // Get sequence
    $length = strspn($startString, '1234567890', $position);
    $prefix = substr($startString, 0, $position);
    $suffix = substr($startString, $position + $length);
    $start  = substr($startString, $position, $length);
    $end    = substr($endString, $position, $length);
    if ($start < $end) {
        if ($step <= 0) {
            throw new LogicException('Step must be positive');
        }
        for ($i = $start; $i <= $end; $i += $step) {
            yield $prefix . str_pad($i, $length, "0", STR_PAD_LEFT) . $suffix;
        }
    } else {
        if ($step >= 0) {
            throw new LogicException('Step must be negative');
        }
        for ($i = $start; $i >= $end; $i += $step) {
            yield $prefix . str_pad($i, $length, "0", STR_PAD_LEFT) . $suffix;
        }
    }
}

仅当

时范围长度相等时才有效