問題描述
我有一個字符串說:Order_num = "0982asdlkj"
我怎樣才能把它分成 2 個變量,用數字元素,然后在 php 中用字母元素另一個變量?
How can I split that into the 2 variables, with the number element and then another variable with the letter element in php?
number 元素可以是 1 到 4 之間的任意長度,字母元素填充其余部分,使每個 order_num 總共有 10 個字符.
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.
我找到了 php explode
函數......但不知道如何在我的情況下實現它,因為數字的數量在 1 到 4 之間,之后的字母是隨機的,所以無法在特定字母處拆分.請盡可能具體的幫助!
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!
推薦答案
您可以使用 preg_split
使用 前瞻和后視:
print_r(preg_split('#(?<=d)(?=[a-z])#i', "0982asdlkj"));
印刷品
Array
(
[0] => 0982
[1] => asdlkj
)
這僅在字母部分確實只包含字母而沒有數字時才有效.
This only works if the letter part really only contains letters and no digits.
更新:
只是為了澄清這里發生的事情:
Just to clarify what is going on here:
正則表達式查看每個位置,如果該位置之前有一個數字((?<=d)
)和之后的一個字母((?=[az])
),然后它匹配并且字符串在這個位置被拆分.整個事情不區分大小寫(i
).
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
).
這篇關于PHP 將字符串拆分為整數元素和字符串的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!