preg_match用于查找URL中的当前目录

时间:2010-05-12 10:25:57

标签: php regex preg-match

我正在尝试通过检查URL中的最终目录来检测用户正在查看的网站的当前部分。我正在使用PHP和正则表达式进行操作,我认为我很接近,但遗憾的是还没有完成。

以下是我目前的情况:

<?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.";
    }
?>

我在if语句之前放置了echo,只是为了确认$ url的值。这输出

/currentdirectory/file.php

但条件本身并不匹配任何内容,我的每个部分的回声都不会显示。

此外,如果有更简单的方法,那么我愿意接受建议。

由于

3 个答案:

答案 0 :(得分:2)

为什么不使用dirname

答案 1 :(得分:0)

好的,我现在有了原始解决方案:

<?php
    $_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.";
    }
?>

但是继Emil的评论后,我现在看到有一个更简单的方法,我也有这个工作:

<?php   
    $section = dirname($_SERVER['PHP_SELF']) . "/";

    if ($section == "/one/") {
        echo "one";
    } elseif ($section == "/two/") {
        echo "two";
    } elseif ($section == "/three/") {
        echo "three";
    } elseif ($section == "/four/") {
        echo "four";
    } elseif ($section == "/five/") {
        echo "five";
    } elseif ($section == "//") {
        echo "global";
    }
?>

我只是想我会在这里发布这两种方法,以防它们对其他人有用。

答案 2 :(得分:0)

或者您可以使用parse_url

执行此操作