You can use preg_match_all like this:
$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 version
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 is not worth the overhead to use regex if you still need to quote to add a delimiter. Just use explode and add 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 a solution using one regular expression 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 demonstration
nickb source share