【问题标题】:escape string but not in "'s转义字符串但不在 "'s
【发布时间】:2014-04-02 23:50:31
【问题描述】:

我有一个类似的字符串:

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

我想变成这样

'word1 
word2 "word3 \nword4" word5 
word6'

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

【问题讨论】:

  • 你想在哪里渲染这个字符串?
  • 我要把它写到一个文件中。

标签: php regex pcre


【解决方案1】:

你可以使用 preg_split 来完成这个任务:

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

你在一个数组中获得你想要的部分,你可以制作你想要的所有东西。 (逐行写入文件,使用 CRLF 内爆......)

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-24
      • 2017-09-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多