MeltingDog
MeltingDog

Reputation: 15414

Using Regex to detect if string exists

I need to use PHP's preg_match() and Regex to detect the following conditions:

If a URL path is one of the following:

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

Answers (2)

The fourth bird
The fourth bird

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
    • | Or
    • products/[a-zA-Z0-9_ ]+ Match products/, match 1+ times what is listed
  • ) Close group

Regex demo

Note that [a-zA-Z0-9_ ]+ might be shortened to [\w ]+

Upvotes: 1

Code Maniac
Code Maniac

Reputation: 37755

You can use alternation

([\w ]+)\/products|products\/([\w ]+)

enter image description here

Regex Demo

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

Related Questions