【问题标题】:Matching strings that contain words with at least 2 spaces匹配包含至少 2 个空格的单词的字符串
【发布时间】:2016-03-18 03:26:45
【问题描述】:

我需要匹配包含至少 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 个,或者如果有任何空格,则不应匹配字符串中不是单词或空格的其他字符。

【问题讨论】:

标签: php regex preg-match-all


【解决方案1】:

试试这个

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

Demo

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

【讨论】:

    猜你喜欢
    • 2023-03-24
    • 2022-11-19
    • 2015-08-23
    • 1970-01-01
    • 1970-01-01
    • 2012-07-24
    • 1970-01-01
    • 2017-10-16
    • 1970-01-01
    相关资源
    最近更新 更多