PHP将字符串拆分为整数元素和字符串 [英] PHP split string into integer element and string

查看:315
本文介绍了PHP将字符串拆分为整数元素和字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串说:Order_num = "0982asdlkj"

在php中,如何将其分为2个变量,分别是数字元素和数字元素,然后是数字元素?

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的任何长度,而letter元素将填充其余部分,使每个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)) 之前,并且在其后的字母((?=[a-z]))之后,则它匹配并且字符串在这个位置.整个过程都不​​区分大小写(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将字符串拆分为整数元素和字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆