問(wèn)題描述
我有一個(gè)字符串說(shuō):Order_num = "0982asdlkj"
我怎樣才能把它分成 2 個(gè)變量,用數(shù)字元素,然后在 php 中用字母元素另一個(gè)變量?
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 之間的任意長(zhǎng)度,字母元素填充其余部分,使每個(gè) order_num 總共有 10 個(gè)字符.
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
函數(shù)......但不知道如何在我的情況下實(shí)現(xiàn)它,因?yàn)閿?shù)字的數(shù)量在 1 到 4 之間,之后的字母是隨機(jī)的,所以無(wú)法在特定字母處拆分.請(qǐng)盡可能具體的幫助!
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
)
這僅在字母部分確實(shí)只包含字母而沒(méi)有數(shù)字時(shí)才有效.
This only works if the letter part really only contains letters and no digits.
更新:
只是為了澄清這里發(fā)生的事情:
Just to clarify what is going on here:
正則表達(dá)式查看每個(gè)位置,如果該位置之前有一個(gè)數(shù)字((?<=d)
)和之后的一個(gè)字母((?=[az])
),然后它匹配并且字符串在這個(gè)位置被拆分.整個(gè)事情不區(qū)分大小寫(xiě)(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
).
這篇關(guān)于PHP 將字符串拆分為整數(shù)元素和字符串的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!