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

I am trying to break / blow / preg_split a string, but I want to keep the separator 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 need to execute a loop and then re-prefix the array values ​​or if there is a cleaner way.

I tried preg_split () with PREG_SPLIT_DELIM_CAPTURE, but I get something line by line:

 array('/block/, 2/page/2', '/block/, 3/page/4'); 

This is not what I want. Any help is greatly appreciated.

+4
source share
2 answers

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

+7
source

Keep in mind that:

 explode('/block/', '/block/2/page/2/block/3/page/4'); 

will result in:

 array("", "2/page/2", "3/page/4"); 

You can use preg_match_all as

 preg_match_all(":(/block/.*?):", $string); // untested 

But just adding a separator is a much clearer solution.

+1
source

Source: https://habr.com/ru/post/1383532/


All Articles