在同一字符出现 1 次或多次后拆分字符串
我无法弄清楚如何将字符串拆分为相同字符的组。我有一些与此类似的相当随机的字符组字符串:
$string = 'aaabb2222eee77777';
我希望能够像这样分割它们:
['aaa', 'bb', '2222', 'eee', '77777']
然后能够计算每组中的字符数。做到这一点最简单的方法是什么?
I'm having trouble figuring out how to split a string into groups of identical characters. I have a few strings of rather random character groups similar to this one:
$string = 'aaabb2222eee77777';
I would like to be able to split them like so:
['aaa', 'bb', '2222', 'eee', '77777']
and then be able to count the number of characters in each set. What would be the easiest way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
然后,您可以迭代该数组并获取每个项目的
strlen()
:You can then iterate through the array and get the
strlen()
of each item:如果您不想声明新的引用变量来保存结果数组,或者不想填充二维数组,或者更喜欢直接返回所需的平面结果数组,请使用
preg_split() 而不是
preg_match_all()
。捕获任意一个字符,然后匹配该字符的零个或多个后续副本,然后用
\K
忘记这些字符——这将允许该函数在每个重复序列之后在零宽度位置上进行分割人物。代码:(Demo)
要查找每个元素的长度,只需使用
strlen()
循环调用。 (演示)If you don't want to declare a new reference variable to hold the result array, or don't want to populate a 2d array, or prefer to directly return the desired flat result array, then use
preg_split()
instead ofpreg_match_all()
.Capture any one character, then match zero or more subsequent copies of that character, then forget those characters with
\K
-- this will allow the function to split on the zero-width position after each sequence of repeated characters.Code: (Demo)
To find the lengths of each element, just make
strlen()
calls in a loop. (Demo)