[英]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);
可以用一個漂亮的正則表達式來完成,但是更容易失敗和解釋需要更長的時間。 就像是
/(?::keyword_start:|\G(?!^)\S+)\K(?<!_end:)\s+/
好吧,我的php不好,因此無論語言如何,我都會給出解決方案。 這將對您有所幫助,因為您可以選擇語言並同樣實施。
所以解決。 嗯,在兩個keywords
之間找不到double space
的簡單方法。 可能會有一些優秀的正則表達式。 但是我的方法很簡單。
步驟1:使用(?<=:keyword_start:).*?(?=:keyword_end:)
實現keywords
之間的文本。
步驟2:使用簡單的\\s+
替換找到的文本中的double spaces
或multiple tabs
。
如果希望正則表達式替換所有空格,包括制表符和空行,則可以使用以下命令:
$s = preg_replace('/\s+/', ' ', $s);
即使字符之間只有一個,它也將替換TAB和換行符。 多個(任何)空格也將減少為一個空格字符。
這里僅用於多個空格的正則表達式(但在這種情況下,像在另一個答案中那樣使用str_replace更快)
$s = preg_replace('/ */', ' ', $s);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.