Regex to match 2 or more words

冷暖自知 提交于 2019-12-02 13:14:26

问题


I have a regex that tries to match for 2 or more words, but it isn't working as it's suppose to. What am I doing wrong?

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

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

Expected Result:

Array ( i dont know )

Actual Result:

Array ( )


回答1:


This will match for string that contains 2 words or more exactly:

/([a-zA-Z]+\s?\b){2,}/g you can go http://www.regexr.com/ and test it

PHP:

$string = "i dont know , do you know?";
preg_match("/([a-zA-Z]+\s?\b){2,}/", $string, $match);

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

Note: do not use the /g in the PHP code




回答2:


This one should work: ~([\w']+(\s+|[^\w\s])){2,}~g, which also match string like "I do!"

Test it here




回答3:


I think you are missing how the {} are used, to match two words

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

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

}

Match is

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

Match will have all matches of the pattern, so then its trivial to just count them up...

When using

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

Match is

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

clearly not what you want.

The only way I see with preg_match is with this /([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

Suggested

preg_match_all ([a-z]+) http://www.phpliveregex.com/p/frR ( may have to select preg_match_all on the site )



来源:https://stackoverflow.com/questions/36817529/regex-to-match-2-or-more-words

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!