Split string in at new line, unless new line in quotes

前端 未结 2 1275
星月不相逢
星月不相逢 2021-01-29 11:08

Can I split a string at new lines, unless the new line is inside a quote?

$string = \'aa\\nbb\\n\"cc\\ndd\"\';
$arr = explode(\"\\n\", $string);
//$arr = array(\         


        
相关标签:
2条回答
  • 2021-01-29 11:51

    Based on your explode() call, I am going to assume that you have made a mistake in posting your sample input and that your actual input generates the sample output that you have provided.

    You can split the newlines that are not wrapped in double quotes by using (*SKIP)(*FAIL) to consume and disqualify quoted substrings, then just explode on the newlines.

    Admittedly, this will not be reliable if your text might contain escaped double quote characters -- because the pattern will treat the escaped quote the same as an unescaped quote.

    Code: (Demo)

    $text = <<<TEXT
    aa\nbb\n"cc\ndd"
    TEXT;
    
    var_export(preg_split('~"[^"]*"(*SKIP)(*FAIL)|\n~', $text));
    

    Output:

    array (
      0 => 'aa',
      1 => 'bb',
      2 => '"cc
    dd"',
    )
    
    0 讨论(0)
  • 2021-01-29 11:53

    In your example, '...\n...' is not a newline, as axiac points out. Newlines in PHP are more easily represented with double quotes, so that PHP interprets them as newlines. Perhaps you meant the following:

    $string = "aa\nbb\n\"cc\ndd\"";
    

    If this is the case, you can create a regex-style split like this, which should catch all the newlines that are not between quotes:

    $arr = preg_split("/(\n)(?=(?:[^\"]|\"[^\"]*\")*$)/m", $string);
    

    Note the multi-line flag (m), since you're dealing with newlines.

    0 讨论(0)
提交回复
热议问题