我试图通过检查URL中的最终目录来检测用户正在查看的网站的当前部分。我使用PHP和正则表达式来做到这一点,我想我很接近,但不幸的是还没有完成。preg_match在URL中查找当前目录
这是我目前有:
<?php
$url = $_SERVER['REQUEST_URI_PATH'] = preg_replace('/\\?.*/', '', $_SERVER['REQUEST_URI']);
$one = '/one/';
$two = '/three/';
$three = '/three/';
$four = '/four/';
$five = '/five/';
echo $url;
if (substr($_SERVER['REQUEST_URI_PATH'], 0, strlen($one)) == $one) {
// URI path starts with "/one/"
echo "The section is one.";
}
elseif (substr($_SERVER['REQUEST_URI_PATH'], 0, strlen($two)) == $two) {
// URI path starts with "/two/"
echo "The section is two.";
}
elseif (substr($_SERVER['REQUEST_URI_PATH'], 0, strlen($three)) == $three) {
// URI path starts with "/three/"
echo "The section is three.";
}
elseif (substr($_SERVER['REQUEST_URI_PATH'], 0, strlen($four)) == $four) {
// URI path starts with "/four/"
echo "The section is four.";
}
elseif (substr($_SERVER['REQUEST_URI_PATH'], 0, strlen($five)) == $five) {
// URI path starts with "/five/"
echo "The section is five.";
}
?>
我放在回声$ url的值的if语句只是为了得到确认之前。这种输出
/currentdirectory/file.php
但条件本身不匹配任何内容,我的每一个部分单独回声永远不会显示。
此外,如果有一个更简单的方法做到这一点,那么我接受建议。
感谢
做,我看到了'/ currentDirectory所/'不同于'/一个/','/二/'...'/五类/'。这就是没有人执行if分支的原因。你实际需要什么? – 2010-05-12 14:27:49
对不起,我可能没有让自己清楚。/currentdirectory /旨在表示活动目录(/ one /,/ two /,/ three /等)。我想要一种方法来检测哪个活动目录是,然后采取适当的行动。我设法弄清了这一点,并已复制到下面的替代解决方案。 非常感谢。 – Ian 2010-05-12 15:33:02