我需要一个正则表达式来匹配所有单个单词和每对两个单词


I need a regex to match all single words and every pair of two words

我使用 PHP preg_match_all 函数,我需要它返回每个单词和每对单词的数组,包括那些单个单词,例如:

preg_match_all('/the regex/','Stackoverflow is awesome',$matches);

$matches数组应包含:

("Stackoverflow" , "is" , "awesome" , "

Stackoverflow is" , "is awesome")

我尝试过使用这个正则表达式,但没有得到预期的结果:

[a-z]+''s?[a-z]*

我认为仅使用正则表达式无法实现这一目标。我会说,使用爆炸并自己构造数组。

$string = 'Stackoverflow is awesome';
$parts = explode(' ', $string);
for ($i = 1; $i < count($parts); $i++) {
    $parts[] = $parts[$i - 1] . ' ' . $parts[$i];
}

使用 'S+ 匹配所有单词。接下来你做'S+'s+'S+,它不会匹配之前匹配的字符,因为默认情况下正则表达式不会进行重叠匹配。为了使正则表达式引擎进行重叠匹配,您需要将一次匹配两个单词的模式放在捕获组中,并将捕获组放在正面环视中。

$s = "Stackoverflow is awesome";
$regex = '~(?=('S+'s+'S+))|'S+~';
preg_match_all($regex, $s, $matches);
$matches = array_values(array_filter(call_user_func_array('array_merge', $matches)));
print_r($matches);

输出:

Array
(
    [0] => Stackoverflow
    [1] => is
    [2] => awesome
    [3] => Stackoverflow is
    [4] => is awesome
)

这限制了两个单词的措辞。

<?php
$str = "Stackoverflow is awesome";
$words = explode(" ",$str);
$num_words = count($words);
for ($i = 0; $i < $num_words; $i++) {
  for ($j = $i; $j < $num_words; $j++) {
    $num = 0;
    $temp = "";
    for ($k = $i; $k <= $j; $k++) { 
       $num++;
       $temp .= $words[$k] . " ";             
    }
    if($num < 3)
    echo $temp . "<br />";
  }
}
?>

您可以在此处使用前瞻:

preg_match_all('/(?=('b('w+)(?:'s+('w+)'b|$)))/','Stackoverflow is awesome',$matches);

现在双字:

print_r($matches[1]);
Array
(
    [0] => Stackoverflow is
    [1] => is awesome
    [2] => awesome
)

和单个单词:

print_r($matches[2]);
Array
(
    [0] => Stackoverflow
    [1] => is
    [2] => awesome
)

PS:awesome用双字打印也是因为它是最后一个词。

试试这个简单的正则表达式

 /'w+/i

重写:

     preg_match_all('/'w+/i','Stackoverflow is awesome',$matches);
 print_r($matches);

在此处查看此内容的实际效果