I have a search box. When user enters a single character like ‘A’ or ‘B’ or ‘C’. Instead of running a query on my database, I redirect them to appropriate page of a to z directory
So for example if a user search’s for ‘H’ they get taking to www.domain.com/a_to_z/h/
To achieve this I have
if($_GET[search] == "a") echo header("location:/a_to_z/a/");
if($_GET[search] == "b") echo header("location:/a_to_z/b/");
if($_GET[search] == "c") echo header("location:/a_to_z/c/");
This works but as you can see it’s not very efficient.
I know it’s possible开发者_开发问答 to accomplish this with a single line using prge_match but I don’t know how to actually do it.
Your help will be much appreciated
Thanks
The regex [a-z]
will only match a single character from lowercase a to lowercase z. To include uppercase and numbers, use [a-zA-Z0-9]
instead. It's probably what you're looking for:
if (preg_match('~^[a-z]$~', $_GET['search'])) {
// redirect
} else {
// handle errors
}
This is a good site for the various regular expression basics.
header("location:/a_to_z/".$_GET[search]."/");
take on mind that $_GET[search] isn't validated in any way here
精彩评论