代码之家  ›  专栏  ›  技术社区  ›  Prashanth Benny

php-preg\u split()具有多个模式,不拆分带引号的字符串

  •  1
  • Prashanth Benny  · 技术社区  · 6 年前

    我需要把一段话分成几个句子。 这就是我和正则表达式有点混淆的地方。

    我已经提到这个了 question 此Q标记为复制到的。但这里的问题不同。

    下面是我需要拆分的字符串示例:


    生活,自由的生活。”不是吗?”

    $sentence_array = preg_split('/([.!?\r\n|\r|\n])+(?![^"]*")/', $paragraph, -1);
    

    array (  
      [0] => "hello"  
      [1] => "how are you"  
      [2] => "how is life"  
      [3] => "live life, live free"  
      [4] => ""isnt it?""  
    )
    

    我得到的是:

    array(
      [0] => "hello! how are you? how is life live life, live free. "isnt it?""
    )
    

    感谢您的帮助。非常感谢。

    2 回复  |  直到 6 年前
        1
  •  2
  •   revo shanwije    6 年前

    正则表达式存在一些问题,主要是将组构造与字符类混淆。烟斗 | | 真的。没有什么特别的意义。

    你需要的是:

    ("[^"]*")|[!?.]+\s*|\R+
    

    首先尝试匹配一个用双引号括起来的字符串(并捕获内容)。然后尝试匹配 [!?.] 准备和他们分开。如果找到了任何类型的换行符。

    菲律宾比索:

    var_dump(preg_split('~("[^"]*")|[!?.]+\s*|\R+~', <<<STR
    hello! how are you? how is life
    live life, live free. "isnt it?"
    STR
    , -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY));
    

    输出:

    array(5) {
      [0]=>
      string(5) "hello"
      [1]=>
      string(11) "how are you"
      [2]=>
      string(11) "how is life"
      [3]=>
      string(20) "live life, live free"
      [4]=>
      string(10) ""isnt it?""
    }
    
        2
  •  1
  •   Tim Biegeleisen    6 年前

    当看到这个标点符号后跟双引号时。

    双引号。这意味着在使用lookarounds的以下模式上进行拆分:

    (?<=[.!?\r\n])(?=[^"])|(?<=[.!?\r\n]")(?=.)
    

    $input = "hello! how \"are\" \"you?\" how is life\nlive life, live free. \"isnt it?\"";
    $sentence_array = preg_split('/(?<=[.!?\r\n])(?=[^"])|(?<=[.!?\r\n]\")(?=.)/', $input, -1);
    print_r($sentence_array);
    
    Array ( [0] => hello! [1] => how "are" "you?" [2] => how is life
        [3] => live life, live free. [4] => "isnt it?" )