Search code examples
phparraysstringassociative-arraytext-parsing

Parse string of alternating letters and numbers (no delimiters) to associative array


I need to parse a string of alternating letters and number and populate an array where the letters are the keys and the numbers are the values.

Example:

p10s2z1234

Output

Array(
    'p' => 10,
    's' => 2,
    'z' => 1234
)

Solution

  • Use regex to get desired values and then combine arrays to get associative array. For example:

    $str = 'p10s2z1234';
    
    preg_match_all('/([a-z]+)(\d+)/', $str, $matches); //handles only lower case chars. feel free to extend regex
    
    print_r(array_combine($matches[1], $matches[2]));