正则表达式匹配2个或更多单词

时间:2016-04-23 23:16:34

标签: php regex preg-match

我有一个试图匹配2个或更多单词的正则表达式,但它不能正常工作。我做错了什么?

$string = "i dont know , do you know?";
preg_match("~([a-z']+\b){2,}~", $string, $match);

echo "<pre>";
print_r($match);
echo "</pre>";

预期结果:

数组(我不知道)

实际结果:

Array()

3 个答案:

答案 0 :(得分:2)

这将匹配包含2个或更多单词的字符串:

$string = "i dont know , do you know?"; preg_match("/([a-zA-Z]+\s?\b){2,}/", $string, $match); echo "<pre>"; print_r($match); echo "</pre>"; 您可以http://www.regexr.com/进行测试

PHP:

getApplicationContext()

注意:不要在PHP代码中使用/ g

答案 1 :(得分:0)

这个应该有效:function writeResponse(resp, cb) { fs.writeFile('response.json', JSON.stringify(resp, null, 2), function (err) { if (err) console.log(err); if(cb) cb(); }); } ,它也匹配html { display: table; width: 100%; min-height: 100%; } body { display: table-row; } .sidebar { width: 250px; display: table-cell; vertical-align: top; min-height: 100%; } .sidebar + .content { display: table-cell; vertical-align: top; min-height: 100%; } html, .sidebar, .sidebar + .content { border: 1px solid #f00; }

之类的字符串

测试here

答案 2 :(得分:-1)

我认为您错过了如何使用{}来匹配两个单词

preg_match_all('/([a-z]+)/i', 'one two', $match );

if( $match && count($match[1]) > 1 ){
         ....

}

匹配

array (
  0 => 
  array (
    0 => 'one',
    1 => 'two',
  ),
  1 => 
  array (
    0 => 'one',
    1 => 'two',
  ),
)

匹配将具有该模式的所有匹配,因此只需将它们计算起来......

使用时

        preg_match('/(\w+){2,}/', 'one two', $match );

匹配

 array (
      0 => 'one',
      1 => 'e',
 )

显然不是你想要的。

我使用preg_match看到的唯一方法是/([a-z]+\s+[a-z]+)/

preg_match ([a-z']+\b){2,} http://www.phpliveregex.com/p/frM

preg_match ([a-z]+\s+[a-z]+) http://www.phpliveregex.com/p/frO

建议的

preg_match_all ([a-z]+) http://www.phpliveregex.com/p/frR(可能必须在网站上选择preg_match_all)