Search code examples
phpregexsplitdelimiterpreg-split

Split a string just before each occurrence of 3 specific delimiters


I'm a bit lost with preg_split() in parsing a string with multiple delimiters and keeping the delimiter in the 'after' part of the split.

My delimiters are $, #, and ?.

For instance:

$str = 'participant-$id#-group';
$ar = preg_split('/([^$#?]+[$#?]+)/', $str, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
echo "<pre>";  print_r( $ar); echo "</pre>";

will show:

Array
(
    [0] => participant_data-$
    [1] => id#
    [2] => -group
)

However I need:

Array
(
    [0] => participant_data-
    [1] => $id
    [2] => #-group
)

Regex makes my brain hurt. so could someone advise how I use PREG_SPLIT_DELIM_CAPTURE and keep the delimiter at the beginning of the segment?


Solution

  • Try this:

    $ar = preg_split('/(\$[^#]+)/', $str, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);