modrewrite for smart URL's | multiple variables?
Wha开发者_JS百科t is the best way to accomplish that?
Im planning to do some kind of smart modrewrite + a function to grab variable name from the URL.
For example:
A URL like: domain.com/page-blog/id-5/title-a_blog_title/date-2011_08_05
Would return:
$urlvariable = page-blog/id-5/title-a_blog_title/date-2011_08_05
Than, I will run a function that will parse the $urlvariable and return
$urlvariable['page'] = blog
$urlvariable['id'] = 5
$urlvariable['title'] = a_blog_title
$urlvariable['date'] = 2011_08_05
But the rewrite should be able to handle smaller or bigger urls like: domain.com/page-blog/id-5/
returning:
$urlvariable = page-blog/id-5/
or also: domain.com/page-blog/id-5/title-a_blog_title/date-2011_08_05/var1-foo/var2-bar/var3-xpto/var4-xyz etc ...
$urlvariable = page-blog/id-5/title-a_blog_title/date-2011_08_05/var1-foo/var2-bar/var3-xpto/var4-xyz
Any way to do that? What would be the expression for rewrite?
Thanks,
As for me, the best way is to route all request to your php/another_language script and then use something like this:
for($i=1,$arr=explode('/',$_SERVER['REQUEST_URI']),$s=count($arr);$i<$s;++$i){ //avoid 0(empty part) and 1(script name)
$tmp=explode(' ',$arr[$i]);
$get[$tmp[0]]=$tmp[1];
}
RiaD has the right idea, using explode
rather than regexps (since regexps are slower).
However, you might want to use regular expressions anyway to "normalize" the URL. But after that you can still use explode
for a tiny speed gain, or do something like this
$url = "page-blog/id-5/blank-/title-a_blog_title/date-2011_08_05/var1-foo/var2-bar/var3-xpto/var4-xyz";
$url = preg_replace("~//+~", '/', $url); // remove multiple consequtive slashes
$params = array();
if( preg_match_all("~(\w+)-([^/]*)~", $url, $params) ) {
$params = array_combine($params[1], $params[2]);
print_r($params);
}
That will print:
Array(
[page] => blog
[id] => 5
[blank] =>
[title] => a_blog_title
[date] => 2011_08_05
[var1] => foo
[var2] => bar
[var3] => xpto
[var4] => xyz
)
精彩评论