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

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.

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).

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.