dpbrrczhlwbv849228 2013-04-02 16:26
浏览 45

使用PHP更改基于URI的href

I'm trying to make a main menu bar link dynamic, based on the visitor's current page.

I started with

 $path = $_SERVER['REQUEST_URI'];

Which, of course, returns things like

  • /subfolder/page.html
  • /subfolder1/subfolder2/page.html
  • /page.html

I need to grab whatever is after the first '/'. I've tried messing around with explode, but I stumble with what to do with the resulting array. I'm also going cross-eyed trying to write a regex - seems a more elegant solution.

Then I need to build my switch. Something along the lines of:

switch ($path)
{
case '/subfolder0':
  $link = $root_url.'/subfolder0/anotherfolder/page.html';
  break;
case '/subfolder1':
  $link = $root_url.'/subfolder1/page.html';
  break;
default:
  $link = $root_url.'/subfolder2/page.html';
}

Finally, should I be using if...elseif for this in lieu of switch?

Thanks for your time, all!

  • 写回答

4条回答 默认 最新

  • dongnaoben4456 2013-04-02 16:31
    关注

    To grab everything after the first /:

    strstr($_SERVER['REQUEST_URI'], '/');
    

    Or, with regex:

    preg_match('#(/.*)#', $_SERVER['REQUEST_URI'], $matches);  // $matches[1] will be the path
    

    As far as the switch, I'd say if/elseif/else is the least-elegant in your case, switch isn't bad, but personally I'd go with an associative array:

    $mapping = array('/subfolder0' => $root_url.'/subfolder0/anotherfolder/page.html', 'etc' => 'etc');
    $link = $mapping($path);
    

    This lets you keep the mapping in another file for organization, and makes it a little bit easier to maintain by separating configuration from implementation.

    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题