2017-03-17 335 views
1

我想返回三個詞組短語的每個實例的匹配。我現在不擔心正確的語法。我更關心如何實現請求的「多通」性質。正則表達式匹配每3個字符串

$string = "one two three four five"; 

$regex = '/(?:[^\\s\\.]+\\s){3}/ui'; 

preg_match_all($regex, $string, $matches); 

只會返回:

one two three

所需的結果:

one two three

two three four

three four five

+0

什麼是有問題的正則表達式的輸出? – user961954

回答

8

你可以做到這一點把你的模式在先行:

$string = "one two three four five"; 

$regex = '~\b(?=([^\s.]+(?:\s[^\s.]+){2}))~u'; 

preg_match_all($regex, $string, $matches); 

print_r($matches[1]); 
+0

這很好,謝謝。即使角色類在「^ \ s」(除了空格外的任何東西)上匹配,它也會在連字符上分裂。你會如何解決這個問題? – atb

+1

@atb:可以用'(?<![^ \ s。])*替換字邊界'\ b'來解決這個問題。*(不是以一個不是空格或點的字符開頭)* –

2

這將是更容易使用explode()

$string = "one two three four five"; 
$arr = explode(" ", $string); 

for ($i = 0; $i < 3; $i++) 
    echo $arr[$i], " ", $arr[$i + 1], " ", $arr[$i + 2], "\n"; 

輸出:

一二三

一二三四

三四五

0

看來你需要將字符串分割成一個數組。

$string = "one two three four five"; 
    $stringSplit[] = $string.Split(' '); 
    $finalArray = []; 

然後遍歷數組。數組中的每個元素都與它後面的兩個元素連接起來。

for(int I=0; I<$stringSplit.length - 3; I++){ 
     $secondString = I + 1; 
     $thirdString = I + 2; 
     $finalArray[I] = $stringSplit[I] + $stringSplit[$secondString] + $stringSplit[$thirdString]; 
}