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 <
Regex is painfully slow. A better method is removing escaped characters from the string prior to splitting then putting them back in:
$foo = 'a,b|,c,d||,e';
function splitEscaped($str, $delimiter,$escapeChar = '\\') {
//Just some temporary strings to use as markers that will not appear in the original string
$double = "\0\0\0_doub";
$escaped = "\0\0\0_esc";
$str = str_replace($escapeChar . $escapeChar, $double, $str);
$str = str_replace($escapeChar . $delimiter, $escaped, $str);
$split = explode($delimiter, $str);
foreach ($split as &$val) $val = str_replace([$double, $escaped], [$escapeChar, $delimiter], $val);
return $split;
}
print_r(splitEscaped($foo, ',', '|'));
which splits on ',' but not if escaped with "|". It also supports double escaping so "||" becomes a single "|" after the split happens:
Array ( [0] => a [1] => b,c [2] => d| [3] => e )