PHP Explode KK599

Hi, just a quick one (I think), how would I go about exploding KK599 into KK and 599. Not sure how I can do this. I know I could do if I had a hyphen separating them but my boss wants it to be all together.

Not the cleanest, but hopefully the gist is there.


<?php
error_reporting(-1);
ini_set('display_errors', true);

function parse($str){
  $parts = array();
  preg_match('~([a-z]+)(\\d+)?~i', $str, $parts);
  return $parts;
}

var_dump(
  parse('KK599')
);

/*
  array(3) {
    [0]=>
    string(5) "KK599"
    [1]=>
    string(2) "KK"
    [2]=>
    string(3) "599"
  }
*/

var_dump(
  parse('A12345')
);

/*
  array(3) {
    [0]=>
    string(6) "A12345"
    [1]=>
    string(1) "A"
    [2]=>
    string(5) "12345"
  }
*/

var_dump(
  parse('ABC')
);

/*
  array(2) {
    [0]=>
    string(3) "ABC"
    [1]=>
    string(3) "ABC"
  }
*/

You can’t do that using explode. You’d better a regular expression. Something like


$var='KK599';
preg_match('~([A-Z]+)(\\d+)~', $var, $matches);
echo $matches[1]; // KK
echo $matches[2]; // 599

HTH :slight_smile:

Edit:

@Anthony : ARGH! Ya beat me to it! :stuck_out_tongue:

Here’s another quicky: sscanf('KK599', '%[A-Z]%d', $letters, $number); (:

I tried sscanf! Ashamedly I didn’t read the manual and assumed it only took a sprintf style format. Thus didn’t work.

Good show Salathe, as always. :wink:

Hey guys, thanks for your messages, massive help, that’s sorted that problem out. Appreciate the help as always! :smiley: