Freddie Freddie - 2 months ago 14
PHP Question

Get range letter and number with php

how can I get range for bottom string in php?


I want result


this is what i do

$string = "M0000001:M0000100";
$explode = explode(":",$string );
$text_one = $explode[0];
$text_two = $explode[1];
$range = range($text_one,$text_two);

So can anyone help me with this?


This is one of many ways you could do this and this is a little verbose but hopefully it shows you some "steps" to take.

It doesn't check for the 1st number being bigger than the 2nd.

It doesn't check your Range strings start with a "M".

It doesn't have all of the required comments.

Those are things for you to consider and work out...

$string = "M00000045:M000099";
echo generate_range_from_string($string);

function generate_range_from_string($string) {
// First explode the two strings
    $explode  = explode(":", $string);
    $text_one = $explode[0];
    $text_two = $explode[1];
// Remove the Leading Alpha character
    $range_one      = str_replace('M', '', $text_one);
    $range_two      = str_replace('M', '', $text_two);
    $padding_length = strlen($range_one);
// Build the output string
    $output = '';
    for ( $index = (int) $range_one; $index <= (int) $range_two; $index ++ ) {
        $output .= 'M' . str_pad($index, $padding_length, '0', STR_PAD_LEFT) . '<br>';

    return $output;

The output lists a String in the format you have specified in the question. So this is based solely upon that.

This could undergo a few more revisions to make it more function like, as I'm sure some folks will pick out!