Anton Anton - 1 year ago 90
PHP Question

Split string by delimiter, but not if it is escaped

How can I split a string by a delimiter, but not if it is escaped? For example, I have a string:


The delimiter is
and an escaped delimiter is
. Furthermore I want to ignore escaped backslashes, so in
would still be a delimiter.

So with the above string the result should be:

[0] => 1
[1] => 2\|2
[2] => 3\\
[3] => 4\\\|4

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download