Url routing regex help
I'm trying to create a url routing script for my new CMS but must confess that regex isn't my strong side. So far i keep running into errors or no results.
What i'm trying to accomplish is using certain tags like :id
:year
:slug
etc...
Can anybody help me out or guide me to the right direction with this, that is how to use preg_match or similar functions to find the right "url pattern"? Goog开发者_JS百科le has not been doing it job for once :S
ADDED
Example url http://www.mysite.com/post/2011/08/15/title-of-a-blogg-post/
If i have a route database and one pattern is for example post/:year/:month/:day/:slug
i want it to match this pattern and call a certain controller, action and in this example a certain article.
The regex array i created looks like
$patterns = array(
":id" => "/^[0-9]*$/",
":year" => "/^([0-9]{4})*$/",
":year_short" => "/^([0-9]{2})*$/",
":month" => "/^([0-9]{2})*$/",
":day" => "/^([0-9]{2})*$/",
":slug" => "/^[a-zA-Z0-9 -]*$"
);
I reckon i need to replace :id
to /^[0-9]*$/
and afterwards run a preg_match to find if the url pattern exists in my routes table. However i don't know if i'm using the right regex patterns or just completely lost.
My .htaccess
file is (because i need to use $_GET as well)
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
I use this basically to fetch the url and leave out $_GET variables.
$route_orginal = trim($_SERVER["REQUEST_URI"]);
if(strpos($route_orginal, "?")!=FALSE) {
list($route_orginal, $get_orginal) = explode("?", trim($_SERVER["REQUEST_URI"]));
}
if( substr($route_orginal,(strlen($route_orginal)-1),strlen($route_orginal)) == "/") {
$this->routes = substr($route_orginal,1,(strlen($route_orginal)-2));
} else {
$this->routes = substr($route_orginal,1,strlen($route_orginal));
}
I'm not sure what you are trying to accomplish.
But if you want a URL like www.mysite.com/tags/id-year-slug
where every tag is seperated by a hyphen, you could do like this:
First, you need a .htaccess file in your root to create pretty urls.
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/tags/([A-Za-z-]+)$ index.php?tags=$1 [L,QSA]
Then in your index, you explode the tags by the - delimiter:
$tags = explode('-',$_GET['tags']);
Now you have an array of tags, which you can use for your sql and the url is pretty - high five!
精彩评论