2017-02-19 61 views
0

我有一个接收一个参数,以打印页面,这样的PHP文件中只有最后一个部分:如何写一个重写规则传递路径

build.php?parameter=print-this-article 

而且我要的是创造一个RewriteRule.htaccess,让我非常最后一部分发送到PHP文件,无论级别,例如:

www.mysite.com/article/level-1/level-2/level-3 

因此,在这种情况下,build.php将接收参数level-3

但是,如果用户键入以下URI:

www.mysite.com/article/level-1/level-2 

它的工作是这样的:

build.php?parameter=level-2 

而且同样具有level-1 ...

是否有一个解决方案?

+0

试图更好地解释这个问题 – Stratboy

回答

0

为了获得水平,你必须捕捉请求URI的一部分。为确保它是最后一部分,它不得包含任何斜杠。这是由这个正则表达式

RewriteRule ([^/]+)$ build.php?parameter=$1 [L] 

最重要的部分是[^/],这是一个character class[...],包括任何not^斜线/认可。

0

我研究了更多并结束了混合PHP和RewriteRule

.htaccess我写道:

# this sends the whole part of the URI that is after the 'article/' 
RewriteRule ^article/(.+)$ build.php?parameter=$1 [L] 

因此,如果URI是www.mysite.com/article/level-1/level-2 PHP文件build.php将收到此字符串level-1/level-2

而在build.php我添加了这个功能:

function get_last_parameter($link) 
    { 
     // to split the string right on the '/' 
     $parts = explode("/", $link); 
     // to remove empty elements, this helps in case a URI ended with '/' is received 
     $parts = array_diff($parts, array('')); 
     // take the final element of the array and remove any string that starts with '#', so it won't be confused with sections 
     $final_array = explode("#", end($parts)); 
     // the result is an array of two (or more elements) so send the first one (of this array) 
     $parameter = reset($final_array); 
     return $parameter; 
    } 
// ... and wrote the query to select from the database the article 

这种方法的好处是,我可以在同一时间使用URI的所有的“水平”,因为我将拥有完整的阵列。