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

前端 未结 2 1282
星月不相逢
星月不相逢 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 = <<

    Output:

    array (
      0 => 'aa',
      1 => 'bb',
      2 => '"cc
    dd"',
    )
    

提交回复
热议问题