I'd like to do a preg_match on a uri string with optional and required parts but I can't figure it out.
Example to match:
/segment/(required)/segment(/optional)
I want both strings below to match against the above
/segment/required/segment/optional
and
/segment/reguired/segment
I know the policy is to not write for me but I can't figure this out so thought I'd at least ask.
Adding ? after the non-capturing group makes the whole non-capturing group optional. Alternatively, you could do: \".
$ means "Match the end of the string" (the position after the last character in the string).
The question mark makes the preceding token in the regular expression optional. E.g.: colou?r matches both colour and color.
You can make several tokens optional by grouping them together using round brackets, and placing the question mark after the closing bracket. E.g.: Nov(ember)? will match Nov and November.
You can write a regular expression that matches many alternatives by including more than one question mark. Feb(ruary)? 23(rd)? matches February 23rd, February 23, Feb 23rd and Feb 23.
Source: http://www.regular-expressions.info/optional.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With