我想为三个单词短语的每个实例返回匹配项。我现在不担心正确的语法。我对如何实现请求的“多次传递”性质更感兴趣。
$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 :(得分:8)
你可以把你的模式放在前瞻中:
$string = "one two three four five";
$regex = '~\b(?=([^\s.]+(?:\s[^\s.]+){2}))~u';
preg_match_all($regex, $string, $matches);
print_r($matches[1]);
答案 1 :(得分: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";
输出:
一二三
二三四
三四五