James Craig
James Craig

Reputation: 6854

Regex: Match Optional URI Parameters

Take a given URI, like this:

one/two/three

How would I match each character, in a capture group, between the slashes? This can be done with this method:

(.+)\/(.+)\/(.+)

This gives me three groups where:

$1 = one
$2 = two
$3 = three

What I am having trouble with is making a capture group optional. I thought that this would work, thinking I could make each group optional (match zero or more):

(.+)?\/(.+)?\/(.+)?

Is there a way, using Regex or PHP to optionally match parts one, two or three of the above URI?

Upvotes: 1

Views: 102

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626870

You can use the following regex

^(?:(.+?))?(?:\/(.+?))?(?:\/(.+?))?$

This will make all groups optional. The main point is using non-capturing groups with ? quantifier, and .+? patterns to capture each part into separate group, so that you could reference them later with $n.

See example.

Sample code:

$re = "/^(?:(.+?))?(?:\\/(.+?))?(?:\\/(.+?))?$/m"; 
$str = "one/two/three\none/two\none\n\n"; 
preg_match_all($re, $str, $matches);

Upvotes: 1

Related Questions