Grumblesaurus
Grumblesaurus

Reputation: 3119

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.

Upvotes: 0

Views: 61

Answers (2)

Barmar
Barmar

Reputation: 780724

If you put the delimiter in a capture group, they'll be included in the preg_split() result, but as separate elements. So you'll get

["1d20", "+", "3d6", "-", "4d8", "+", "10"]

Another option is to use preg_match_all() instead of preg_split(), and make the operator an optional pattern at the beginning of the regexp that matches the items.

preg_match_all('/[-+]?[^-+]+/', $string, $matches);

Upvotes: 1

Nick
Nick

Reputation: 147146

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

Upvotes: 1

Related Questions