John Smith
John Smith

Reputation: 495

How can I merge this RegEx code

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.

Upvotes: 0

Views: 68

Answers (1)

mario
mario

Reputation: 145482

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.

Upvotes: 5

Related Questions