代码之家  ›  专栏  ›  技术社区  ›  Shobi

只匹配单词之间空格的正则表达式[重复]

  •  1
  • Shobi  · 技术社区  · 6 年前

    我只想删除引号之间的空格,比如:

    $text = 'good with spaces "here all spaces should be removed" and here also good';
    

    有人能帮上忙吗?我已经试过了:

    $regex = '/(\".+?\")|\s/';
    

    $regex = '/"(?!.?\s+.?)/';
    

    但没有成功,我发现一个样本的工作方向是错误的:-( Removing whitespace-characters, except inside quotation marks in PHP? 但我不能改变。

    泰晤士报

    0 回复  |  直到 6 年前
        1
  •  3
  •   Casimir et Hippolyte    6 年前

    这种问题很容易解决 preg_replace_callback . 其思想是提取引号之间的子字符串,然后在回调函数中对其进行编辑:

    $text = preg_replace_callback('~"[^"]*"~', function ($m) {
        return preg_replace('~\s~', '#', $m[0]);
    }, $text);
    

    这是最简单的方法。


    用一个单一的模式来做这件事要复杂得多 preg_replace 但有可能:

    $text = preg_replace('~(?:\G(?!\A)|")[^"\s]*\K(?:\s|"(*SKIP)(*F))~', '#', $text);
    

    demo

    图案细节:

    (?:
        \G (?!\A)  # match the next position after the last successful match
      |
        "          # or the opening double quote
    )
    [^"\s]*        # characters that aren't double quotes or a whitespaces
    \K             # discard all characters matched before from the match result
    (?:
        \s         # a whitespace
      |
        "           # or the closing quote
        (*SKIP)(*F) # force the pattern to fail and to skip the quote position
                    # (this way, the closing quote isn't seen as an opening quote
                    # in the second branch.)
    )
    

    这种方式使用 \G 锚定以确保所有匹配的空格都位于引号之间。

    边缘情况:

    • ~(?:\G(?!\A)|"(?=[^"]*"))[^"\s]*\K(?:\s|"(*SKIP)(*F))~

    • 双引号可以包含必须忽略的转义双引号:必须这样描述转义字符:

      ~(?:\G(?!\A)|")[^"\s\\\\]*+(?:\\\\\S[^"\s\\\\]*)*+(?:\\\\?\K\s|"(*SKIP)(*F))~


    \s(?=[^"]*+(?:"[^"]*"[^"]*)*+")
    

    这是一个短模式,但对于长字符串来说可能会有问题,因为对于每个带有空格的位置,您必须检查字符串,直到最后一个带有lookahead的引号。

        2
  •  0
  •   Jan    6 年前

    请参见以下代码段:

    <?php
    $text = 'good with spaces "here all spaces should be removed" and here also good';
    echo "$text \n";
    $regex = '/(\".+?\")|\s/';
    $regex = '/"(?!.?\s+.?)/';
    $text = preg_replace($regex,'', $text);
    echo "$text \n";
    ?>
    

    我发现 a sample that works


    @格雷厄姆:对
    $text = 'good with spaces "here all spaces should be removed" and here also good'
    should be 
    $text = 'good with spaces "hereallspacesshouldberemoved" and here also good';