0

Is it possible when using preg_split to return the delimiters into an array in the order that they were found?

So take this for example:

$string = "I>am+awesome";
preg_split("/>|\+/", $string);

and then get an output somewhat like this:

Array(
    Array(
        0 => "I",
        1 => "am",
        2 => "awesome"
    ),
    Array (
        0 => ">"
        1 => "+"
    )
)

I realize that I could do the split, and then loop through the original string and add them as they are found, but I am looking for a better way if there is one.

Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338

3 Answers3

1

Use a capture group () and PREG_SPLIT_DELIM_CAPTURE:

preg_split("/(>|\+)/", $string, 0, PREG_SPLIT_DELIM_CAPTURE);

Or as @hsz states (>|\+) would be a better pattern.

AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
1

Here is a way to achieve this with lookahead and without using PREG_SPLIT_DELIM_CAPTURE to make this regex work on other platforms like Java where there is no such flag:

print_r( preg_split('/(?<=[>|+])|(?=[>|+])/', $string ) );
Array
(
    [0] => I
    [1] => >
    [2] => am
    [3] => +
    [4] => awesome
)
anubhava
  • 761,203
  • 64
  • 569
  • 643
0
$str = "I+>amaw+e+s>om>e";
$matches =  preg_split("/(>|\+)/",$str);
$all_matches = preg_split("/(>|\+)/", $str ,null, PREG_SPLIT_DELIM_CAPTURE);
$delimeters_order = array_diff($all_matches,$matches);
var_dump($delimeters_order);

array(6) {
 [1]=>
 string(1) "+"
 [3]=>
 string(1) ">"
 [5]=>
 string(1) "+"
 [7]=>
 string(1) "+"
 [9]=>
 string(1) ">"
 [11]=>
 string(1) ">"
}
voodoo417
  • 11,861
  • 3
  • 36
  • 40