1

I want to return matches for every instance of a three word phrase. I'm not worried about proper grammar right now. I'm more interested in how to achieve the 'multi-pass' nature of the request.

$string = "one two three four five";

$regex = '/(?:[^\\s\\.]+\\s){3}/ui';

preg_match_all($regex, $string, $matches);

Will only return:

one two three

Needed results:

one two three

two three four

three four five

1
  • What is the output with regex in question? Commented Mar 17, 2017 at 21:41

2 Answers 2

8

You can do it putting your pattern in a lookahead:

$string = "one two three four five";

$regex = '~\b(?=([^\s.]+(?:\s[^\s.]+){2}))~u';

preg_match_all($regex, $string, $matches);

print_r($matches[1]);
Sign up to request clarification or add additional context in comments.

2 Comments

This is great, thanks. It's splitting on hyphens as well even though the character class is matching on ^\s (anything but space). How would you solve for that?
@atb: it can be solved replacing the word-boundary \b with (?<![^\s.]) (not preceded by a character that is not a white-space or a dot)
2

It would be easier to use explode().

$string = "one two three four five";
$arr = explode(" ", $string);
               
for ($i = 0; $i < 3; $i++) 
    echo $arr[$i], " ", $arr[$i + 1], " ", $arr[$i + 2], "\n";

Outputs:

one two three

two three four

three four five

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.