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:
$matches = array();
preg_match_all('/(\/block\/[0-9]+\/page\/[0-9]+)/', '/block/2/page/2/block/3/page/4', $matches);
var_dump( $matches[0]);
Output:
array(2) {
[0]=>
string(15) "/block/2/page/2"
[1]=>
string(15) "/block/3/page/4"
}
Demo
Edit: This is the best I could do with preg_split.
$array = preg_split('#(/block/)#', '/block/2/page/2/block/3/page/4', -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
$result = array();
for( $i = 0, $count = count( $array); $i < $count; $i += 2)
{
$result[] = $array[$i] . $array[$i + 1];
}
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:
$delimiter = '/block/'; $results = array();
foreach( explode( $delimiter, '/block/2/page/2/block/3/page/4') as $entry)
{
if( !empty( $entry))
{
$results[] = $delimiter . $entry;
}
}
Demo
Final Edit: Solved! Here is the solution using one regex, preg_split
, and PREG_SPLIT_DELIM_CAPTURE
$regex = '#(/block/(?:\w+/?)+(?=/block/))#';
$flags = PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY;
preg_split( $regex, '/block/2/page/2/block/3/page/4', -1, $flags);
preg_split( $regex, '/block/2/page/2/order/title/sort/asc/block/3/page/4', -1, $flags);
Output:
array(2) {
[0]=>
string(15) "/block/2/page/2"
[1]=>
string(15) "/block/3/page/4"
}
array(2) {
[0]=>
string(36) "/block/2/page/2/order/title/sort/asc"
[1]=>
string(15) "/block/3/page/4"
}
Final Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With