PHP split string into integer element and string(PHP 将字符串拆分为整数元素和字符串)
问题描述
我有一个字符串说: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 将字符串拆分为整数元素和字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:PHP 将字符串拆分为整数元素和字符串


基础教程推荐
- php 7.4 在写入变量中的 Twig 问题 2022-01-01
- Yii2 - 在运行时设置邮件传输参数 2022-01-01
- PHPUnit 的 Selenium 2 文档到底在哪里? 2022-01-01
- Web 服务器如何处理请求? 2021-01-01
- 使用 scandir() 在目录中查找文件夹 (PHP) 2022-01-01
- 主题化 Drupal 7 的 Ubercart “/cart"页 2021-01-01
- 将变量从树枝传递给 js 2022-01-01
- php中的PDF导出 2022-01-01
- php中的foreach复选框POST 2021-01-01
- 如何在数学上评估像“2-1"这样的字符串?产生“1"? 2022-01-01