PHP 将字符串拆分为整数元素和字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4537994/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP split string into integer element and string
提问by David19801
I have a string say: Order_num = "0982asdlkj"
我有一个字符串说: Order_num = "0982asdlkj"
How can I split that into the 2 variables, with the number element and then another variable with the letter element in php?
我怎样才能把它分成 2 个变量,用数字元素,然后在 php 中用字母元素另一个变量?
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.
数字元素可以是从 1 到 4 的任意长度,字母元素填充其余部分,使每个 order_num 总共有 10 个字符。
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!
我找到了 phpexplode
函数......但不知道如何在我的情况下制作它,因为数字的数量在 1 到 4 之间,之后的字母是随机的,所以无法在特定的字母处拆分。请尽可能具体的帮助!
回答by Felix Kling
You can use preg_split
using lookahead and lookbehind:
您可以使用preg_split
使用前瞻和后视:
print_r(preg_split('#(?<=\d)(?=[a-z])#i', "0982asdlkj"));
prints
印刷
Array
(
[0] => 0982
[1] => asdlkj
)
This only works if the letter part really only contains letters and no digits.
这只适用于字母部分真的只包含字母而没有数字的情况。
Update:
更新:
Just to clarify what is going on here:
只是为了澄清这里发生的事情:
The regular expressions looks at every position and if a digit is before that position ((?<=\d)
) anda letter after it ((?=[a-z])
), then it matches and the string gets split at this position. The whole thing is case-insensitive (i
).
正则表达式查看每个位置,如果在该位置之前有一个数字 ( (?<=\d)
)并且在它之后是一个字母 ( (?=[a-z])
),那么它匹配并且字符串在这个位置被拆分。整个过程不区分大小写 ( i
)。
回答by moinudin
Use preg_match()with a regular expression of (\d+)([a-zA-Z]+)
. If you want to limit the number of digits to 1-4 and letters to 6-9, change it to (\d+{1,4})([a-zA-Z]{6,9})
.
将preg_match()与正则表达式(\d+)([a-zA-Z]+)
. 如果要将数字限制为 1-4,字母限制为 6-9,请将其更改为(\d+{1,4})([a-zA-Z]{6,9})
。
preg_match("/(\d+)([a-zA-Z]+)/", "0982asdlkj", $matches);
print("Integer component: " . $matches[1] . "\n");
print("Letter component: " . $matches[2] . "\n");
Outputs:
输出:
Integer component: 0982
Letter component: asdlkj
回答by codaddict
回答by BoltClock
You can use a regex for that.
您可以为此使用正则表达式。
preg_match('/(\d{1,4})([a-z]+)/i', $str, $matches);
array_shift($matches);
list($num, $alpha) = $matches;
回答by Wazy
Check this out
看一下这个
<?php
$Order_num = "0982asdlkj";
$split=split("[0-9]",$Order_num);
$alpha=$split[(sizeof($split))-1];
$number=explode($alpha, $Order_num);
echo "Alpha -".$alpha."<br>";
echo "Number-".$number[0];
?>
with regards
带着敬意
wazzy
昏昏沉沉的