逃避字符串但不在"' s

时间:2014-04-02 23:50:31

标签: php regex pcre

我有一个字符串:

'word1 \nword2 "word3 \nword4" word5 \nword6'

我希望变得像

'word1 
word2 "word3 \nword4" word5 
word6'

我无法写任何成功的正则表达式模式。这可能吗?

2 个答案:

答案 0 :(得分:0)

您可以使用preg_split执行此任务:

$result = preg_split('/"[^"]*"(*SKIP)(*FAIL)|\s*\\n\s*/', $txt);

您可以在阵列中获得所需的部件,然后可以制作出您想要的所有部件。 (逐行写一个文件,用CRLF内爆......)

有关(*SKIP)(*FAIL)的更多信息:Verbs that act after backtracking and failure

答案 1 :(得分:0)

有可能通过正则表达式,我的方式有点复杂,也许有人有更好的解决方案

$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);