lmshaffe lmshaffe - 1 year ago 82
PHP Question

Regex for URL Redirecting

Currently have a regex rule


The purpose of this was to capture URLs with /connect or /connect?whatever. I'm now having an issue where /connecticut is getting captured, but I do not want it to. I've been playing around for a while, but having the query param on the URL is tripping me up in getting this to work. Anybody have any suggestions so that /connecticut is not captured, but the other two are?

Answer Source

You may use an optional group around \?.* and make the ? obligatory inside it and add an end of string $ anchor:


See the regex demo

Pattern details:

  • ^ - start of string
  • \/connect - a literal substring /connect
  • (?:\?.*)? - an optional group that matches 1 or 0 sequences of:
    • \? - a literal ? symbol
    • .* - zero or more characters other than newline, as many as possible up to...
  • $ - end of string.