我想为我的新CMS创建一个url路由脚本,但必须承认,正则表达式不是我强烈的一面。到目前为止,我仍然遇到错误或没有结果。Url路由正则表达式帮助
我想要做到的是使用特定的标签,如:id
:year
:slug
等等
任何人可以帮助我或引导我与这个方向是正确的,那就是如何使用的preg_match或类似函数来找到正确的“url模式”?谷歌尚未这样做的工作一次:S
ADDED
示例URL http://www.mysite.com/post/2011/08/15/title-of-a-blogg-post/
,如果我有一个路由数据库和一个模式是例如post/:year/:month/:day/:slug
我希望它匹配这个模式,调用某个控制器,并在此示例中调用某个文章。
正则表达式阵列我创建看起来像
$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 -]*$"
);
我想我需要更换:id
到事后运行的preg_match找到,如果URL模式在我的路由表中存在。不过,我不知道我是使用正确的正则表达式模式还是完全丢失。
我.htaccess
文件(因为我需要使用$ _GET以及)
RewriteEngine On
RewriteBase/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
我用这个基本上是获取网址,并留下了$ _GET变量。
$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));
}
该手册解释了正则表达式模式http://www.php.net/manual/en/reference.pcre.pattern.syntax.php和http://regular-expressions.info/是一个有用的介绍。像http://stackoverflow.com/questions/89718/is-there-anything-like-regexbuddy-in-the-open-source-world这样的工具可以帮助制作它们。 – mario
您能否为您的问题添加更多细节?什么是输入,代码和解释什么不起作用以及您最终期望得到什么结果。 – stema
希望我添加的代码解释了它更好一点我想要完成的事情 – dansige