Jump to content

Match string with any character (greedy), including spaces, etc.


br3nn4n

Recommended Posts

So I'm venturing into mod_rewrite, which (as you probably know) uses regex to match a pattern so it knows when to rewrite the URL.

 

I have a url like so:

 

http://example.com/search/here's where the search terms go!

 

And I need to find the part in bold for my RewriteRule to work. It works with single, non-spaced containing queries. I need it to also match queries with spaces, quotes, etc.

 

Here's what I got so far

 

RewriteRule ^search/([.][\s][a-zA-Z0-9]+)(/)?$ index.php?page=search&query=$1 [NC,L]

 

I've also tried

 

RewriteRule ^search/([.\s][a-zA-Z0-9]+)(/)?$ index.php?page=search&query=$1 [NC,L]

 

But neither is working. I'd love some assistance :D

Link to comment
Share on other sites

A dot inside a character class (square brackets) is treated like a literal dot. Try something like

 

RewriteRule ^search/(.+)/?$ index.php?page=search&query=$1 [NC,L]

 

An optional trailing slash won't be part of the search term. And an ampersand will terminate the search string.

Link to comment
Share on other sites

Almost; the plus quantifier means one or more times.

 

But actually I was a bit wrong, an optional trailing slash will be part of the search term. To exclude it you can use this instead:

 

RewriteRule ^search/(.+?)/?$ index.php?page=search&query=$1 [NC,L]

 

The question mark makes the dot lazy, so it will stop at the optional trailing slash (but only because of the dollar sign right after it, matching at the end of the string).

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.