【问题标题】:I need a regex to match all single words and every pair of two words我需要一个正则表达式来匹配所有单个单词和每对两个单词
【发布时间】:2015-03-16 15:32:30
【问题描述】:

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

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

$matches 数组应包含:

('Stackoverflow' , 'is' , 'awesome' , 'Stackoverflow is' , '很棒')

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

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

【问题讨论】:

标签: php regex preg-match-all


【解决方案1】:

我认为您无法仅使用正则表达式来实现。我想说,使用explode并自己构造数组。

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

【讨论】:

  • 我最终使用了您的答案,但我使用 preg_split("/[\s,.]+/", $string) 函数代替了爆炸,因为我正在处理自然文本(使用逗号等)
【解决方案2】:

使用\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
)

【讨论】:

    【解决方案3】:

    这将短语限制为两个单词。

    <?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 />";
      }
    }
    ?>
    

    【讨论】:

      【解决方案4】:

      您可以在此处使用前瞻:

      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 打印成双字也是因为它是最后一个字。

      【讨论】:

        【解决方案5】:

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

         /\w+/i
        

        重写:

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

        查看实际情况here

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-10-15
          • 1970-01-01
          • 2017-10-27
          • 2017-07-21
          • 1970-01-01
          相关资源
          最近更新 更多