PHP上的两个连续单词正则表达式


two consecutive words regular expression on PHP

我是正则表达式的新手;我想制作一个正则表达式来选择两个连续的单词。我找到了一个相关的话题,但没有得到正确的答案。

例如,这里有一个短语:彩色图像处理;

它必须返回以下几个字:

彩色图像

图像处理

处理

我使用了/'w{1,}'s'w{1,}/,但它返回:

彩色图像

处理;

您可以在此处使用Positive Lookahead。

preg_match_all('/(?=([a-z]+'s+[a-z]+))[a-z]+/i', $text, $matches);
print_r($matches[1]);

输出

Array
(
    [0] => Color Image
    [1] => Image Processing
    [2] => Processing with
)
$string = "Color Image Processing with ;";
$wordPairs = array();
preg_match_all('~'w+~',$string,$words);
foreach ($words[0] as $i => $word) {
  if (isset($words[0][$i+1]))
    $wordPairs[] = $word . ' ' . $words[0][$i+1];
}
print_r($wordPairs);
/* output */
Array
(
    [0] => Color Image
    [1] => Image Processing
    [2] => Processing with
)