douwu3763 2011-08-16 13:50
浏览 15
已采纳

带有preg_match的PHP菜单

First sorry for my bad English.

I have this menubar in PHP. I want that if an user is on a page the current menuitem gets another color. I had a code that works, but if i have a page like /item.php?id=9 , it wont work. So i tried this with preg_match, but i can't get it to work.

Menu :

<li <?php unset($pageURL); getSelected("/index.php") ?>><a href="index.php">Home</a></li>
<li <?php unset($pageURL); getSelected("/item.php") ?>><a href="item.php">Item</a></li>
<li <?php unset($pageURL); getSelected("/more.php") ?>><a href="more.php">More</a></li>

Function getSelected:

Function getSelected($nameURL){
$curURL =$_SERVER["REQUEST_URI"];
$pattern = "~$nameURL/.*~";
    if(preg_match($pattern, $curURL)){
        echo 'class="selected"';
        unset($curURL);
    }
    unset($curURL);
}

How can i fix this with preg_match?

Thank you!

  • 写回答

5条回答 默认 最新

  • dpb42021 2011-08-16 14:04
    关注

    I think basename() in combination with parse_url() would do the job. It returns the filename of an URL:

    function getSelected($nameURL){
        $currentfile = basename(parse_url($_SERVER['REQUEST_URI'],PHP_URL_PATH));
        if($currentfile === $nameURL){
            echo 'class="selected"';
        }
    }
    

    And in HTML e.g.:

    <li <?php getSelected("item.php") ?>><a href="item.php">Item</a></li>
    

    No need for RegEx here.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失