I have a string like:
'word1 \nword2 "word3 \nword4" word5 \nword6'
and I want to became like
'word1 
word2 "word3 \nword4" word5 
word6'
I couldn't write any success regexp pattern. Is this possible ?
I have a string like:
'word1 \nword2 "word3 \nword4" word5 \nword6'
and I want to became like
'word1 
word2 "word3 \nword4" word5 
word6'
I couldn't write any success regexp pattern. Is this possible ?
 
    
    You can use preg_split for this task:
$result = preg_split('/"[^"]*"(*SKIP)(*FAIL)|\s*\\n\s*/', $txt);
You obtain the parts you want in an array, you can make all what you want after. (write a file line by line, implode with a CRLF...)
More informations about (*SKIP) and (*FAIL): Verbs that act after backtracking and failure
 
    
     
    
    It's possible by regex, my way is kinda complex, maybe someone has better solution
$subject = <<<'SUBJECT'
'word1 \nword2 "special \n \"character" word5 \nword6'
SUBJECT;
$callback = function ($matches1) {
    if (preg_match_all(
<<<PATTERN
/"(?:\"|[^"])+?"/
PATTERN
        , $matches1[0], $matches2, PREG_OFFSET_CAPTURE)) {
        $pointer = 0;
        $arr = [];
        foreach ($matches2[0] as $match2) {
            $arr[] = substr($matches1[0], $pointer, $match2[1]);
            $arr[] = $match2[0];
            $pointer = $match2[1] + strlen($match2[0]);
        }
        $arr[] = substr($matches1[0], $pointer, strlen($matches1[0]));
        foreach ($arr as $key => &$value) {
            if (!($key % 2)) { 
                $value = preg_replace('/\Q\n\E/', "\n", $value); 
            }
        }
        return implode('', $arr);
    }
    return $matches1[0];
};
$result = preg_replace_callback(
<<<PATTERN
/'(?:\'|[^'])+?'/
PATTERN
, $callback, $subject);
file_put_contents('doc.txt', $result);
