TheAngryCube
TheAngryCube

Reputation: 45

preg_split does not split multiple delimiters

I'm trying to split a simple string by multiple delimiters, but get an unexpected result.

Consider the following string: "1_10_10-Einzel.pdf"

Using this call to preg_split:

$cut = preg_split("/[_\-\.]/", "1_10_10-Einzel.pdf", PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE);
print_r($cut);

I expect the following output:

Array
(
    [0] => 1
    [1] => 10
    [2] => 10
    [3] => Einzel
    [4] => pdf
)

, but actually what I get is this:

Array
(
    [0] => 1
    [1] => 10
    [2] => 10-Einzel.pdf
)

I played around a little bit with parentheses, flags and of course different regexes, but I don't get the expected behaviour. I also tried some completely different examples from stackOverflow, but also got a wrong result. Do I miss something?

Upvotes: 1

Views: 120

Answers (1)

user3783243
user3783243

Reputation: 5224

Parameter 3 is the limit, 4 is for flags. Try:

$cut = preg_split("/[_.-]/", "1_10_10-Einzel.pdf", -1, PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE);
print_r($cut);

https://3v4l.org/hheJg

. doesn't need to be escaped in a character class. The - also doesn't if first or last.

Upvotes: 3

Related Questions