Serhat
Serhat

Reputation: 396

Matching first four words with regex

I am trying to match the first 4 words in the input string.

My pattern: ([\w\’\s{3}])+

My content: test1 test2 test3 test4 test5 test6 test7

I want to get: test1 test2 test3 test4

All alphabetic characters and there are max 3 spaces.

Upvotes: 0

Views: 1743

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627292

While you could perhaps just use explode(" ", $s), and then take the first 4 elements and imlode them back, a fixed regex solution is

$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

See the IDEONE demo and here is the regex demo.

The preg_match finds the first occurrence of 4 words matched with

  • (?:[\w\']+\s+){3} - 3 sequences of 1+ word chars or ' symbol followed with 1+ whitespaces
  • [\w\']+ - 1+ word or ' chars.

Upvotes: 2

Related Questions