开发者

How do i break string into words at the position of number

I have some string data with alphanumeric value. like us01name, phc01name and other i.e alphabates + number + alphabates.

i would like开发者_StackOverflow社区 to get first alphabates + number in first string and remaining on second.

How can i do it in php?


You can use a regular expression:

// if statement checks there's at least one match
if(preg_match('/([A-z]+[0-9]+)([A-z]+)/', $string, $matches) > 0){
    $firstbit = $matches[1];
    $nextbit  = $matches[2];
}

Just to break the regular expression down into parts so you know what each bit does:

(              Begin group 1
  [A-z]+         As many alphabet characters as there are (case agnostic)
  [0-9]+         As many numbers as there are
)              End group 1
(              Begin group 2
  [A-z]+         As many alphabet characters as there are (case agnostic)
)              End group 2


Try this code:

preg_match('~([^\d]+\d+)(.*)~', "us01name", $m);
var_dump($m[1]); // 1st string + number
var_dump($m[2]); // 2nd string

OUTPUT

string(4) "us01"
string(4) "name"

Even this more restrictive regex will also work for you:

preg_match('~([A-Z]+\d+)([A-Z]+)~i', "us01name", $m);


You could use preg_split on the digits with the pattern capture flag. It returns all pieces, so you'd have to put them back together. However, in my opinion is more intuitive and flexible than a complete pattern regex. Plus, preg_split() is underused :)

Code:

$str = 'user01jason';
$pieces = preg_split('/(\d+)/', $str, -1, PREG_SPLIT_DELIM_CAPTURE);
print_r($pieces);

Output:

Array
(
    [0] => user
    [1] => 01
    [2] => jason
)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜