簡體   English   中英

PHP RegEx刪除2個單詞之間的雙倍空格

[英]PHP RegEx to remove double spaces between 2 words

我需要一個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);

誰能幫我 ?

您可以使用\\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

演示

您可以在單詞之間使用回調

$str = preg_replace_callback('/:keyword_start:(.*?):keyword_end:/s', function ($m) {
  return ':keyword_start:' . preg_replace('/\s{2,}/', " ", $m[1]) . ':keyword_end:';
}, $str);
  • 令牌之間的(.*?) 延遲 捕獲$1任意數量的字符
  • \\s{2,}匹配兩個或多個空格
  • 關閉定界符后的s 標志使點與換行符匹配

請參閱eval.in上的演示


可以用一個漂亮的正則表達式來完成,但是更容易失敗和解釋需要更長的時間。 就像是

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

regex101上的演示

好吧,我的php不好,因此無論語言如何,我都會給出解決方案。 這將對您有所幫助,因為您可以選擇語言並同樣實施。

所以解決。 嗯,在兩個keywords之間找不到double space的簡單方法。 可能會有一些優秀的正則表達式。 但是我的方法很簡單。

步驟1:使用(?<=:keyword_start:).*?(?=:keyword_end:)實現keywords之間的文本。

Regex101演示在這里。

步驟2:使用簡單的\\s+替換找到的文本中的double spacesmultiple tabs

Regex101演示在這里。

如果希望正則表達式替換所有空格,包括制表符和空行,則可以使用以下命令:

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

即使字符之間只有一個,它也將替換TAB和換行符。 多個(任何)空格也將減少為一個空格字符。

這里僅用於多個空格的正則表達式(但在這種情況下,像在另一個答案中那樣使用str_replace更快)

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM