tags:

views:

91

answers:

3

Hi all,

Another n00b question.

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

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

What's the easiet single way to convert "ab" to "a" and "b" in both examples above?

Thanks!

+1  A: 

You can do that with a regex:

  $match = preg_match('@^(\w+)(\d+)@', $input);
  $letter = $match[1];
  $number = $match[2];
eWolf
to make this meet the requirements you could alter the regex to exclude preceeding 0's: "@^(\w+)0*(\d+)@"
Kevin Peno
Okay, but if he's using $number as an int, this doesn't matter.
eWolf
+1  A: 
$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

Kevin Peno
This won't work for the second example with $ab = "B01250".
Daok
Updated to assume that the second "part" is always an integer
Kevin Peno
I was toying around with regex first, but I knew there was a more elegant way. Thanks! And thanks to the others as well. :)
RC
+3  A: 

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

Noah
What if 0 isn't the first number after the offset?
Kevin Peno