Alex.Barylski
Alex.Barylski

Reputation: 2933

How do I stop this from being greedy

I have the following regex:

#^/workorder/(.*)/#

Provided the following URI's:

/workorder/archive/2/

The $matches variable from preg_match() is returning archive/2/

Why doesn't the last / in the regex stop the (.*) from being greedy? What do I add to make the regex stop when the / delimiter is found?

Upvotes: 2

Views: 144

Answers (3)

buckley
buckley

Reputation: 14089

To make it not greedy (lazy) use

^/workorder/(.*?)/

But this will use backtracking which is not good for performance. Use

^/workorder/([^/]*)/

To have your cake and eat it fast

Upvotes: 2

Jonathan M
Jonathan M

Reputation: 17451

This will do it.

^/workorder/([^/]*)/

Upvotes: 3

flowfree
flowfree

Reputation: 16462

Replace (.*) with (.*?) to make it non-greedy.

Here's a good explanation: Greedy and Non-Greedy Matches

Upvotes: 3

Related Questions