每三个字符实例后分割一个字符串
如何在每三个分号 (;) 之后的位置分解字符串?
示例数据:
$string = 'piece1;piece2;piece3;piece4;piece5;piece6;piece7;piece8;';
所需输出:
$output[0] = 'piece1;piece2:piece3;'
$output[1] = 'piece4;piece5;piece6;'
$output[2] = 'piece7;piece8;'
请注意,保留尾随分号。
How can I explode a string at the position after every third semicolon (;)?
example data:
$string = 'piece1;piece2;piece3;piece4;piece5;piece6;piece7;piece8;';
Desired output:
$output[0] = 'piece1;piece2:piece3;'
$output[1] = 'piece4;piece5;piece6;'
$output[2] = 'piece7;piece8;'
Notice the trailing semicolons are retained.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
我确信您可以使用正则表达式做一些巧妙的事情,但为什么不直接分解每个半色,然后一次添加三个。
I am sure you can do something slick with regular expressions, but why not just explode the each semicolor and then add them three at a time.
我能想到的最简单的解决方案是:
Easiest solution I can think of is:
本质上与其他
爆炸
并再次加入的解决方案相同......Essentially the same solution as the other ones that
explode
and join again...也许从不同的角度来看待它。将其全部分解,然后将其重新组合成三元组。就像这样...
数组
(
[0] => 1;2;3;
[1] => 4;5;6;
[2] => 7;8;9;
)
Maybe approach it from a different angle. Explode() it all, then combine it back in triples. Like so...
Array
(
[0] => 1;2;3;
[1] => 4;5;6;
[2] => 7;8;9;
)
这是一个正则表达式方法,我不能说它看起来太好了。
输出:
Here's a regex approach, which I can't say is all too good looking.
Output:
另一种正则表达式方法。
结果:
Another regex approach.
Results:
正则表达式拆分
Regex Split
输出
outputs
与 @Sebastian 之前的回答类似,我建议使用重复模式的
preg_split()
。不同之处在于,通过使用非捕获组并附加\K
来重新启动全字符串匹配,您可以省去编写PREG_SPLIT_DELIM_CAPTURE
标志。代码:(Demo)
可以找到一种类似的技术,用于在每 2 个事物之后进行拆分此处。该代码片段实际上在最后一个空格字符之前写入了
\K
,以便在分割时消耗尾随空格。Similar to @Sebastian's earlier answer, I recommend
preg_split()
with a repeated pattern. The difference is that by using a non-capturing group and appending\K
to restart the fullstring match, you can spare writing thePREG_SPLIT_DELIM_CAPTURE
flag.Code: (Demo)
A similar technique for splitting after every 2 things can be found here. That snippet actually writes the
\K
before the last space character so that the trailing space is consumed while splitting.