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

PHP RegEx删除2个单词之间的双空格

  •  1
  • Integer  · 技术社区  · 9 年前

    我需要一个Php RegEx来查找开始关键字和结束关键字之间的所有双空格并删除它们。

    $teststring = 'This is a teststring ... :keyword_start: this is    the content    with double spaces :keyword_end: more text ... :keyword_start: this is the second   content    with double spaces :keyword_end: ... more text';
    

    我需要以下结果:

    This is a teststring ... :keyword_start: this is the content with double spaces :keyword_end: more text ... :keyword_start: this is the second content with double spaces :keyword_end: ... more text
    

    这是我尝试过的:(但它不起作用)

    $teststring = preg_replace('#(:keyword_start:)\s\s+(:keyword_end:)#si', '', $teststring);
    

    有人能帮我吗?

    4 回复  |  直到 9 年前
        1
  •  2
  •   Casimir et Hippolyte    9 年前

    您可以使用 \G 锚此锚点匹配上一次匹配后的位置(默认情况下是字符串的开头)。使用它,您可以获得连续的匹配(直到您打破连续性):

    $pattern = '~(?:\G(?!\A)|:keyword_start:\s)(?:(?!:keyword_end:)\S+\s)*+\K\s+~S';
    
    $result = preg_replace($pattern, '', $str);
    

    图案详细信息:

    ~             # pattern delimiter
    (?:           # non-capturing group
        \G(?!\A)             # contiguous branch (not at the start of the string)
      |                      # OR
        :keyword_start:\s    # start branch
    )
    (?:
        (?!:keyword_end:)\S+ # all non-blank characters that are not the "end word"
        \s                   # a single space
    )*+                   # repeat the group until a double space or the "end word"
    \K                    # remove all on the left from the match result
    \s+                   # spaces to remove
    ~S      # "STUDY" modifier to improve non anchored patterns
    

    demo

        2
  •  1
  •   bobble bubble    9 年前

    您可以使用 callback 字里行间的意思。

    $str = preg_replace_callback('/:keyword_start:(.*?):keyword_end:/s', function ($m) {
      return ':keyword_start:' . preg_replace('/\s{2,}/', " ", $m[1]) . ':keyword_end:';
    }, $str);
    

    See demo at eval.in


    它可以用一个漂亮的正则表达式完成,但更容易失败&解释需要更长时间。有点像

    /(?::keyword_start:|\G(?!^)\S+)\K(?<!_end:)\s+/
    

    Demo at regex101

        3
  •  0
  •   user2705585 user2705585    9 年前

    好吧,我不擅长php,因此我会给出一个解决方案,而不考虑语言。这将很有帮助,因为您可以选择您的语言并同样实现它。

    所以解决方案。好吧,没有一个容易找到的方法 double space 介于两者之间 keywords 。可能有一些 精英 正则表达式。但我的方法相当简单。

    步骤1: 查找之间的文本 关键字 ,使用实现 (?<=:keyword_start:).*?(?=:keyword_end:) .

    Regex101 Demo here.

    第2步: 更换 double spaces multiple tabs 在找到的文本中使用简单 \s+ .

    Regex101 Demo here.

        4
  •  -1
  •   micropro.cz    9 年前

    如果希望正则表达式替换所有空白,包括制表符和空行,可以使用以下方法:

    $s = preg_replace('/\s+/', ' ', $s);
    

    它将替换制表符和换行符,即使只有一个字符。多个(任意)空格也将减少为一个空格字符。

    这里是仅用于多个空格的Regex(但在这种情况下,使用str_replace比在这里的另一个答案中更快)

    $s = preg_replace('/  */', ' ', $s);