将前四个单词与正则匹配

  • 本文关键字:单词 四个 php regex
  • 更新时间 :
  • 英文 :


我试图匹配输入字符串中的前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发现与

匹配的4个单词的首次出现
  • (?:[w']+s+){3}-3个词chars或 '符号的序列,后面是1 whitespaces
  • [w']+-1 word或 ' chars。

最新更新