frosty
frosty

Reputation: 2649

matching everything between two words, while last word being matched is optional

I need to capture everything between 'one' and 'four', the 'four' being optional. We don't know what's between 'one' and 'four'. I tried matching it, but not getting the right result. What am I doing wrong?

$text = "one two three four five six seven eight nine ten";
preg_match("~one( .+)(four)?~i", $text, $match);

print_r($match);

Result:

Array ( [0] => one two three four five six seven eight nine ten [1] => two three four five six seven eight nine ten )

Need Result:

Array ( [0] => one two three four five six seven eight nine ten [1] => two three [3] => four)

PS: Yes, the 'four' needs to be optional.

Upvotes: 1

Views: 55

Answers (2)

Avinash Raj
Avinash Raj

Reputation: 174696

Here you need to use alternation operator.

one(( .+)(four).*|.*)

DEMO

Upvotes: 1

Dmitry
Dmitry

Reputation: 1283

By default repeat operators (like "?", "*", "+" or {n,m}) are greedy - they wil try to match as much symbols as they can. You can read more on this behalf here: What do lazy and greedy mean in the context of regular expressions?

To make them not greedy add "?" after them. Like this: "~one( .+?)(four)?~i"

Upvotes: 0

Related Questions