Reputation: 15414
I need to use PHP's preg_match()
and Regex to detect the following conditions:
If a URL path is one of the following:
products/new items
new items/products
new items/products/brand name
Do something...
I can't seem to figure out how to check if the a string exists before or after the word products. The closest I can get is:
if (preg_match("([a-zA-Z0-9_ ]+)\/products\/([a-zA-Z0-9_ ]+)", $url_path)) {
// Do something
Would anyone know a way to check if the first part of the string exists within the one regex line?
Upvotes: 1
Views: 59
Reputation: 163362
You could use an alternation with an optional group for the last item making the /
part of the optional group.
If you are only looking for a match, you can omit the capturing groups.
(?:[a-zA-Z0-9_ ]+/products(?:/[a-zA-Z0-9_ ]+)?|products/[a-zA-Z0-9_ ]+)
Explanation
(?:
Non catpuring group
[a-zA-Z0-9_ ]+/products
Match 1+ times what is listed in the character class, /
followed by products(?:/[a-zA-Z0-9_ ]+)?
Optionally match /
and what is listed in the character class|
Orproducts/[a-zA-Z0-9_ ]+
Match products/
, match 1+ times what is listed)
Close groupNote that [a-zA-Z0-9_ ]+
might be shortened to [\w ]+
Upvotes: 1
Reputation: 37755
You can use alternation
([\w ]+)\/products|products\/([\w ]+)
Note:- I am not sure how you're using the matched values, if you don't need back reference to any specific values then you can avoid capturing group, i.e.
[\w ]+\/products|products\/[\w ]+
Upvotes: 1