Search code examples
phpregexsplittext-parsingpreg-split

Split an alphanumeric string after each sequence of numbers


I have a series of strings in the form of

10a99b5c
55
2a3b1
g

How can I split the string by the characters (which always appears as a single character between numbers or in the beginning/end of the string)

array([0] => 10a99b5c, [1] => 10, [2]=> a99, [3] => b5, [4] => c),
array([0] => 55, [1] => 55),
array([0] => 2a3b1, [1] => 2, [2] => a3, [3] => b1),
array([0] => g, [1] => g),

The output format is not important, I can handle, I just have no idea what sort of regex pattern can do the trick (even a hint is sufficient).

I do this with preg_replace_callback where I use the digits found for each character for a set of calculations.


Solution

  • Try this:

    $input = ['10a99b5c','55','2a3b1','g'];
    $regEx = '~([a-z]\d*)~';
    
    foreach($input as $str){
      $res[] = preg_split($regEx,$str,-1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
    }
    echo '<pre>';
    var_export($res);
    

    The result for the examples above:

    array (
      0 => 
      array (
        0 => '10',
        1 => 'a99',
        2 => 'b5',
        3 => 'c',
      ),
      1 => 
      array (
        0 => '55',
      ),
      2 => 
      array (
        0 => '2',
        1 => 'a3',
        2 => 'b1',
      ),
      3 => 
      array (
        0 => 'g',
      ),
    )