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.
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_CAPTUREOutput:
Final Demo