RC.
RC.

Reputation: 61

Split string with no delimiter in half (leading letters and trailing number)

How can I separate the leading letter from the trailing number in each of the sample strings AND remove the unneeded zero-padding from the number?

$ab = "A00000001"
echo $a; // gives result "A"
echo $b; // gives result "1"

$ab = "B01250"
echo $a; // gives result "B"
echo $b; // gives result "1250"

Upvotes: -1

Views: 177

Answers (4)

mickmackusa
mickmackusa

Reputation: 48049

The most flexible, direct, and type-considered approach will be to use sscanf(). The function (and its "format" expression) will allow the matching of 1 or more uppercase letters followed by a potentially zero-padded integer.

The output will be a 2-element array containing the leading alphabetical string and then an int-type number. This is great for professional devs that prefer to maintain clean, rigid data types in their applications.

Code: (Demo)

$tests = ['A00000001', 'B01250'];

foreach ($tests as $test) {
    var_export(sscanf($test, '%[A-Z]%d'));
    echo "\n";
}

Output:

array (
  0 => 'A',
  1 => 1,
)
array (
  0 => 'B',
  1 => 1250,
)

sscanf() also permits declaring/populating the variables via parameters. (Demo)

sscanf($test, '%[A-Z]%d', $a, $b);
var_export(['a' => $a, 'b' => $b]);

To retain leading zeros or handle integers greater than PHP allows, replace %d with %[0-9]. This will return the numeric segment as a string.

Upvotes: 0

eflorico
eflorico

Reputation: 3629

You can do that with a regex:

  preg_match('@^(\w)0*(\d+)@', $input, $match);
  $letter = $match[1];
  $number = $match[2];

Upvotes: 1

user67416
user67416

Reputation:

This is shorter, if that's what you mean by "easiet single way":

list($a,$b) = preg_split('/0+/',$ab);

Adjust your regex if you like: http://us.php.net/manual/en/function.preg-split.php

Upvotes: 2

Kevin Peno
Kevin Peno

Reputation: 9206

$ab = "A0000000001";
$a = substr( $ab, 0, 1 );
$b = (int)substr( $ab, 1 );

More information about substr can be found here: http://us.php.net/substr

Upvotes: 0

Related Questions