沃梦达 / 编程问答 / php问题 / 正文

PHP 将字符串拆分为整数元素和字符串

PHP split string into integer element and string(PHP 将字符串拆分为整数元素和字符串)

本文介绍了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 将字符串拆分为整数元素和字符串

基础教程推荐