I would like to strip the leading slash and the querystring from a URL but can’t work out how to do them both. I have this code which works perfectly for stripping the querystring, but it leaves the leading slash
preg_replace('/\?.*$/', '', $_SERVER['REQUEST_URI'])
If my URL is www.mysite.com/myPage?querystring=123, the above leaves me with /myPage. How can I tweak this so I can remove the leading slash too?
Also, can you point me at a resource to help me understand preg_replace pattern matching please?
I might favor PHP’s simple string functions over regex in such a simple case:
PHP’s
strpos()docs returns an integer value, so it’s possible that$q_pos === 0… this is why we check$q_pos !== FALSE.UPDATE
I suppose I should answer the question, though … so to actually use a regex in this situation …
How does this work? Well … our pattern specifies a capture group
([^\?]+)using the parentheses that grabs everything after an optional forward slash/?up to the first occurrence of an optional\?in the string. Note that we escape the actual question mark character with a backslash because it has meaning in the context of regex patterns. The final part of the regex pattern.*simply matches zero or more characters out to the end of the string.Finally, our replacement simply specifies the
$1to reference the text we captured with our original parentheses grouping([^\?]+).One other thing to note that regex novices often fail to realize is that you aren’t required to use
/as pattern delimiters. In a case like this where we’re matching actual forward slash characters I use something else (like the curly braces).I usually point regex beginners to this link to help them get started.
UPDATE 2
The regex above assumes that there is always going to be a query string, so if you run up against a URI that doesn’t have one, (for example,
/All-Products), that regex won’t work. To account for this, simply alter your pattern to make the query string optional:-or-