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

前端 未结 2 1274
星月不相逢
星月不相逢 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: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.

提交回复
热议问题