我正在尝试拆分/分解/preg_split 一个字符串,但我想保留分隔符
我正在尝试拆分/分解/preg_split 一个字符串,但我想保留分隔符示例:
explode('/block/', '/block/2/page/2/block/3/page/4');
预期结果:
array('/block/2/page/2', '/block/3/page/4');
不确定是否必须循环然后重新为数组值添加前缀,或者是否有更干净的方法。
我已经尝试过 preg_split() 和 PREG_SPLIT_DELIM_CAPTURE 但我得到了一些类似的东西:
array('/block/, 2/page/2', '/block/, 3/page/4');
这不是我想要的。非常感谢任何帮助。
I am trying to split/explode/preg_split a string but I want to keep the delimiter example :
explode('/block/', '/block/2/page/2/block/3/page/4');
Expected result :
array('/block/2/page/2', '/block/3/page/4');
Not sure if I have to loop and then re-prefix the array values or if there is a cleaner way.
I have tried preg_split() with PREG_SPLIT_DELIM_CAPTURE but I get something along the lines of :
array('/block/, 2/page/2', '/block/, 3/page/4');
Which is not what I want. Any help is much appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以像这样使用 preg_match_all:
输出:
演示
编辑: 这是我能用 preg_split 做的最好的事情。
如果您仍然需要循环来添加分隔符,那么使用正则表达式的开销是不值得的。只需使用爆炸并自己添加分隔符即可:
演示
最终编辑: 解决了!以下是使用一个正则表达式、
preg_split
和PREG_SPLIT_DELIM_CAPTURE
的解决方案输出:
最终演示
You can use preg_match_all like so:
Output:
Demo
Edit: This is the best I could do with preg_split.
It's not worth the overhead to use a regular expression if you still need to loop to prepend the delimiter. Just use explode and prepend the delimiter yourself:
Demo
Final Edit: Solved! Here is the solution using one regex,
preg_split
, andPREG_SPLIT_DELIM_CAPTURE
Output:
Final Demo
请记住:
将导致:
您可以使用
preg_match_all
之类的但只是在前面加上分隔符是一个更清晰的解决方案。
Keep in mind that:
Will result in:
You could use a
preg_match_all
likeBut just prepending the delimiter is a much clearer solution.
只需使用前瞻即可。这将匹配字符串中每个爆炸点的零宽度位置。要防止在第一次出现之前拆分,请使用
PREG_SPLIT_NO_EMPTY
。代码:(演示)
输出:
Simply use a lookahead. This will match a zero-width position in the string at each point of explosion. To prevent splitting before the first occurrence, use
PREG_SPLIT_NO_EMPTY
.Code: (Demo)
Output: