Split string by delimiter, but not if it is escaped

前端 未结 5 1588
旧巷少年郎
旧巷少年郎 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:19

    Instead of split(...), it's IMO more intuitive to use some sort of "scan" function that operates like a lexical tokenizer. In PHP that would be the preg_match_all function. You simply say you want to match:

    1. something other than a \ or |
    2. or a \ followed by a \ or |
    3. repeat #1 or #2 at least once

    The following demo:

    $input = "1|2\\|2|3\\\\|4\\\\\\|4";
    echo $input . "\n\n";
    preg_match_all('/(?:\\\\.|[^\\\\|])+/', $input, $parts);
    print_r($parts[0]);
    

    will print:

    1|2\|2|3\\|4\\\|4
    
    Array
    (
        [0] => 1
        [1] => 2\|2
        [2] => 3\\
        [3] => 4\\\|4
    )
    

提交回复
热议问题