0

I’ve written this regex code,

/.[^.]*$/ -> file extension

/\?.*/ -> removes everything ?paramternames in PHP

Current usage:

preg_replace('/\?.*/', '', preg_replace('/.[^.]*$/','',basename($_SERVER['REQUEST_URI'])))

How can I make it to a single preg_replace call, instead of these two, is there a way to merge the two RegExes into one single RegEx which does the job?

Can I posted expected output result? Yes.

http://localhost/books.php?tab=to_read

when I run this PHP code with two preg_replaces, I get "books", which I use to highlight in the menu to tell the user current page and menu highlight based on the page URI.

EDIT: There's nothing wrong with this code, it works. However, I want to merge the two regexes into one and only invoke one preg_replace.

3
  • Can you post an example and expected output? Commented Jul 14, 2015 at 18:02
  • URI does not contain query string Commented Jul 14, 2015 at 18:03
  • what output after preg_replace('/.[^.]*$/','',basename($_SERVER['REQUEST_URI'])); ? Commented Jul 14, 2015 at 18:23

1 Answer 1

5

Oftentimes you can just combine two patterns per alternation one|two.

In your case either the "file extension" or the query string might be absent, and they should be matched in the right order. Which is why you should optionalize both parts:

 preg_replace("~ (\.\w+)? (\?.*)?  $   ~x",
                    ↓       ↓      ↓    ↓
                  ".ext"  "?………"  END  readability flag

This ensures the .ext either directly precedes the query string, or spans the last characters itself. Likewise could the query string be optional, but still should match without preceding extension.

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

11 Comments

WOW! This worked. Can you explain this regex in details, thanks?
And it supports all types of extensions? Right? Thanks a lot.
Cool arrows. I need to remember those.
@Qix Kinda got in in the habit lately. They're often mapped to AltGr+U / Y / I.
@N000b101 Now I wouldn't call it bad. You're operating just on the REQUEST_URI here. If this was for a full IRI/URL it would likely mismatch domain names etc. Perhaps not relevant. However it would behave just the same as your original 2×preg_replace approach.
|

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.