将没有分隔符的数字字符串转换为可能为多位数字的数组
如何将没有分隔符的字符串(例如 $a = '89111213';
)拆分为整数数组?
期望的结果:
[8, 9, 11, 12, 13]
我在循环中生成输入数字,并使用 $a .= $somevariable;
之类的串联。
How can I split a string with no delimiters, for example $a = '89111213';
, into an array of integers?
Desired result:
[8, 9, 11, 12, 13]
I generate that input number in a loop with concatenation like $a .= $somevariable;
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
更新:
正如@therefromhere在他的评论中建议的那样,不要将数字连接成一个字符串,而是直接将它们放入一个数组中:
这是一种在某种程度上有效的方法。
重要:
假设:数字按升序连接,并以数字 开头。 10 :)
打印
虽然这可能在某种程度上有效,但在很多情况下会失败。因此:
如何获得
89111213
?如果您从数字 8、9、11 等生成它,您应该生成类似8,9,11,12,13
的内容。Update:
As @therefromhere suggests in his comment, instead of concatenating the numbers into one string,put them in an array directly:
Here is something that works in a way.
Important:
Assumption: Numbers are concatenated in increasing order and start with a number < 10 :)
prints
Although this might work to some extend, it will fail in a lot of cases. Therefore:
How do you obtain
89111213
? If you are generating it from the numbers 8,9,11, etc. you should generate something like8,9,11,12,13
.您可以使用 explode():
You can use explode():
这看起来很危险。您是否将多个数字连接成一个整数?请注意,整数值有上限,因此您可能会遇到许多元素的错误。
另请注意,当数字具有不同长度时,您的问题无法正确解决,因为您无法知道这些组合(如果有)中的哪一个对于
89111213
是正确的:您将需要某种分隔符以使其稳定且面向未来。
This looks dangerous. Have you concatenated several numbers to one integer? Note that there's an upper limit on integer values so you may experience bugs with many elements.
Also note that your problem is not possible to solve correctly when the numbers have different lengths, because you cannot know which of these combinations (if any) is correct for
89111213
:You will need some sort of separator to make it stable and future proof.
这是一个您不需要解决的 XY 问题。首先不要使用串联来构建输入字符串。更改语法以将元素推入平面数组中:
在您的编码要求合法的另一个宇宙中,我有几个解决方案,它们将努力将字符串拆分为递增值的数组(假设数据适应这种拆分) )。
函数式风格:(演示)
使用引用:(演示)
This is an XY Problem that you shouldn't need to solve. Simply don't use concatenation to build the input string in the first place. Change your syntax to push elements into a flat array:
In an alternate universe where your coding requirement is legitimate, I've got a couple of solutions which will endeavor to split the string into an array of increasing values (assuming the data accommodates such splitting).
Functional style: (Demo)
Using references: (Demo)