Reputation: 3119
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
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
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
)
Upvotes: 1