How to separate letters and digits from a string i

2019-01-07 21: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 get "12" "jan" separately..

8条回答
爷、活的狠高调
2楼-- · 2019-01-07 22:14

You can make use of preg_split to split your string at the point which is preceded by digit and is followed by letters as:

$arr = preg_split('/(?<=[0-9])(?=[a-z]+)/i',$str);

Code in Action

<?php
$str = '12jan';
$arr = preg_split('/(?<=[0-9])(?=[a-z]+)/i',$str);                                                               
print_r($arr);

Result:

Array
(
    [0] => 12
    [1] => jan
)
查看更多
欢心
3楼-- · 2019-01-07 22:24
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!

查看更多
登录 后发表回答