Allan Thomas
Allan Thomas

Reputation: 3589

Match from the third word onwards in a string with PHP

I'm trying to return dolor sit amet from the following string -

$title = 'Lorem ipsum dolor sit amet';
preg_match('/^(?:\w+\s+){2}(.)+/', $title, $matches);

It's only matching the last letter.

Upvotes: 0

Views: 509

Answers (2)

aliteralmind
aliteralmind

Reputation: 20163

Try this:

^(?:\w+\s+){2}(.+)$

Regular expression visualization

Debuggex Demo

Putting the plus outside of the capture group: (.)+, as in your original code, is going to capture--potentially--multiple instances of individual characters, when you want to capture is, instead, a single instance of multiple characters.

You're only capturing the final character, instead of the final three words, because it's capturing and then "throwing away" all of these characters...

dolor sit ame

one-by-one, before finally capturing and returning the last t.

Upvotes: 2

Barmar
Barmar

Reputation: 780974

You need to put the repetition operator inside the group:

preg_match('/^(?:\w+\s+){2}(.+)/', $title, $matches);

Otherwise, the group just captures one character.

Upvotes: 3

Related Questions