Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I am trying to split/explode/preg_split a string but I want to keep the delimiter

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.

like image 848
Purplefish32 Avatar asked Feb 23 '23 07:02

Purplefish32


1 Answers

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

like image 191
nickb Avatar answered Mar 11 '23 10:03

nickb