How to separate letters and digits from a string in php

后端 未结 8 2063
攒了一身酷
攒了一身酷 2020-11-29 09:37

I have a string which is combination of letters and digits. For my application i have to separate a string with letters and digits: ex:If my string is \"12jan\" i hav to ge

8条回答
  •  伪装坚强ぢ
    2020-11-29 10:07

    preg_match_all('/^(\d+)(\w+)$/', $str, $matches);
    
    var_dump($matches);
    
    $day = $matches[1][0];
    $month = $matches[2][0];
    

    Of course, this only works when your strings are exactly as described "abc123" (with no whitespace appended or prepended).

    If you want to get all numbers and characters, you can do it with one regex.

    preg_match_all('/(\d)|(\w)/', $str, $matches);
    
    $numbers = implode($matches[1]);
    $letters = implode($matches[2]);
    
    var_dump($numbers, $letters);
    

    See it!

提交回复
热议问题