Split string by delimiter, but not if it is escaped

前端 未结 5 1581
旧巷少年郎
旧巷少年郎 2020-11-27 10:58

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 <

5条回答
  •  感情败类
    2020-11-27 11:14

    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 ) 
    

提交回复
热议问题