匹配包含至少2个空格的单词的字符串

时间:2016-03-18 03:26:45

标签: php regex preg-match-all

我需要匹配包含至少2个空格的字符串。我怎么会在正则表达式中这样做?

$content = "one two three";
preg_match_all("~([\w]+(?:[\s]))+~", $content, $match); 
print_r($match);

结果:

Array ( [0] => Array ( [0] => one two ) [1] => Array ( [0] => two ) )

需要结果:

Array ( [0] => Array ( [0] => one two three))

P:S

请记住,匹配的字符串必须包含至少2个空格,并且字符串必须只包含单词和空格 - 如果字符串中少于2个空格,或者如果有任何空格,则它不应该匹配字符串中不是单词或空格的其他字符。

1 个答案:

答案 0 :(得分:1)

试试这个

^(?=(?:.*?\s){2})[a-zA-Z ]+$

Demo

说明:
(?=(?:.*?\s){2})预测检查至少2个空格 [a-zA-Z ]仅匹配单词和空格。