Skip to content
Advertisement

Split a string by a regex without consuming the delimiter?

I have a string that looks like this:

1d20+3d6-4d8+10

I would like to split that into:

1d20, +3d6, -4d8, +10.

preg_split() consumes the + and - symbols. What is the best way to tell it “split at these symbols, but don’t consume them.”? I can brute force a solution, but I’m guessing there’s a simple solution in the PHP standard library that I’m not familiar with.

Advertisement

Answer

You can split using a zero-width forward lookahead for the delimiter (+ or -):

$string = '1d20+3d6-4d8+10';
print_r(preg_split('/(?=[+-])/', $string));

Output:

Array
(
    [0] => 1d20
    [1] => +3d6
    [2] => -4d8
    [3] => +10
)

Demo on 3v4l.org

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement