我试图匹配输入字符串中的前4个单词。
我的模式: ([w’s{3}])+
我的内容: test1 test2 test3 test4 test5 test6 test7
我想得到: test1 test2 test3 test4
所有字母字符和最大3个空间。
虽然您可以只使用 explode(" ", $s)
,然后将前4个元素和 imlode
拿回去,但固定的正则解决方案是
$re = '~(?:[w']+s+){3}[w']+~';
$str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
preg_match($re, $str, $match);
echo $match[0]; // => Lorem ipsum dolor sit
请参阅IDEONE演示,这是正则演示。
preg_match
发现与
-
(?:[w']+s+){3}
-3个词chars或'
符号的序列,后面是1 whitespaces -
[w']+
-1 word或'
chars。