1

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?

4
  • You looking for something like this ? Commented Sep 2, 2019 at 6:44
  • You can use alternation ([\w_ ]+)\/products|products\/([\w_ ]+) Commented Sep 2, 2019 at 6:47
  • Or '~([^\/]*)(?:^|\/)products(?:\/|$)([^\/]*)~' Commented Sep 2, 2019 at 6:48
  • @WiktorStribiżew but that will match products too Commented Sep 2, 2019 at 6:54

2 Answers 2

1

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 ]+

Sign up to request clarification or add additional context in comments.

3 Comments

This is odd, when I implement it with words other than "product" (as my site requires) it only detects the first instance, eg regex101.com/r/0KfEjo/1
@MeltingDog You have to enable the global flag g at the right top on regex101 regex101.com/r/0KfEjo/2
@MeltingDog But surely do not use any g modifier in PHP code.
1

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 ]+

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.