phpregexpreg-split

How to split string into an alphabetic string and a numeric string?


I need to use preg_split() function to split string into alpha and numeric.

Ex: ABC10000 into, ABC and 10000

GSQ39800 into GSQ and 39800

WERTYI67888 into WERTYI and 67888

Alpha characters will be the first characters(any number of) of the string always and then the numeric(any number of).


Solution

  • This is a tiny task. Use \K with matching on an capital letters in a character class using a one or more quantifier:

    Code:

    $in = 'WERTYI67888';
    var_export(preg_split('/[A-Z]+\K/', $in));
    

    Output:

    array (
      0 => 'WERTYI',
      1 => '67888',
    )
    

    Or if you want the numeric substring to be cast as an integer-type value, use sscanf(). Demo

    $in = 'WERTYI67888';
    var_export(sscanf($in, '%[A-Z]%d'));
    
    array (
      0 => 'WERTYI',
      1 => 67888,
    )