Search code examples
phpregexstringsubstringtext-parsing

Split string only once between sequence of letters and sequence of numbers


I want to extract two substrings from a predictably formatted string.

Each string is comprised of letters followed by numbers.

Inputs & Outputs:

  • MAU120 => MAU and 120
  • MAUL345 => MAUL and 345
  • MAUW23 => MAUW and 23

Solution

  • $matches = array();
    
    if ( preg_match('/^([A-Z]+)([0-9]+)$/i', 'MAUL345', $matches) ) {
        echo $matches[1]; // MAUL
        echo $matches[2]; // 345 
    }
    

    If you require the MAU you can do:

    /^(MAU[A-Z]*)([0-9]+)$/i
    

    Removing i modifier at the end will make the regex case-sensitive.