Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a string say: Order_num = "0982asdlkj"

How can I split that into the 2 variables, with the number element and then another variable with the letter element in php?

The number element can be any length from 1 to 4 say and the letter element fills the rest to make every order_num 10 characters long in total.

I have found the php explode function...but don't know how to make it in my case because the number of numbers is between 1 and 4 and the letters are random after that, so no way to split at a particular letter. Please help as specifically as possible!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
614 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can use preg_split using lookahead and lookbehind:

print_r(preg_split('#(?<=d)(?=[a-z])#i', "0982asdlkj"));

prints

Array
(
    [0] => 0982
    [1] => asdlkj
)

This only works if the letter part really only contains letters and no digits.

Update:

Just to clarify what is going on here:

The regular expressions looks at every position and if a digit is before that position ((?<=d)) and a letter after it ((?=[a-z])), then it matches and the string gets split at this position. The whole thing is case-insensitive (i).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...