Split string by delimiter, but not if it is escaped

php, preg-split, regex

Solution

Use dark magic:

$array = preg_split('~\\\\.(*SKIP)(*FAIL)|\|~s', $string);

`\\\\.` matches a backslash followed by a character, `(*SKIP)(*FAIL)` skips it and `\|` matches your delimiter.

Problem

How can I split a string by a delimiter, but not if it is escaped? For example, I have a string: ``` 1|2\|2|3\\|4\\\|4 ``` The delimiter is `|` and an escaped delimiter is `\|`. Furthermore I want to ignore escaped backslashes, so in `\\|` the `|` would still be a delimiter. So with the above string the result should be: ``` [0] => 1 [1] => 2\|2 [2] => 3\\ [3] => 4\\\|4 ```

Original source

Related problems