如何使用strpos($ _ SERVER [' REQUEST_URI']从网址段

时间:2016-01-20 22:13:35

标签: php navigation strpos

我们已经为此找到了很多答案,但并不完全理解它们(或strpos手册页),如果这已经得到解答,请对不起。

设置:

考虑以下网址......

http://www.domain.com/whats-on/show-name/   
http://www.domain.com/whats-on/show-name/events

以及我们如何在以下列表项标记中应用.active类...

<li>
    <a class="<?= (strpos($_SERVER['REQUEST_URI'], '/whats-on') === 0 ? 'active' : ''); ?>" href="<?= $ShowWhatsOn; ?>">What's on</a>
</li>
<li>
    <a class="<?= (strpos($_SERVER['REQUEST_URI'], '/events') === 0 ? 'active' : ''); ?>" href="<?= $ShowEvents; ?>">Events</a>
</li>

的问题:

  1. 什么是On在“什么”页面上以及“事件”页面上获取活动类,因为/ whats-on也在url中:/ whats-on / show-name /事件

  2. 事件永远不会收到活动类

  3. 问题:

    1. 我们如何使用strpos来检查特定的网址细分,以便在正确的网页上应用.active类?
    2. 我们正在努力保持菜单标记的简短,所以希望有一种方法可以在一行上做到这一点吗?

      非常感谢任何正确方向的帮助或指示。

      干杯

2 个答案:

答案 0 :(得分:2)

strpos为您提供另一个字符串(haystack)中字符串(针)的位置。所以通过做

(strpos($_SERVER['REQUEST_URI'], '/whats-on') === 0

您正在检查REQUEST_URI是否以“/ whats-on”开头(位于0位置)。由于两个URL都以“/ whats-on”开头,因此第一个项目始终处于活动状态,而第二个项目永远不会。

一个解决方法是添加“/ events”检查:

<li>
    <a class="<?= (strpos($_SERVER['REQUEST_URI'], '/whats-on') === 0 && strpos($_SERVER['REQUEST_URI'], '/events') === false ? 'active' : ''); ?>" href="<?= $ShowWhatsOn; ?>">What's on</a>
</li>
<li>
    <a class="<?= (strpos($_SERVER['REQUEST_URI'], '/whats-on') === 0 && strpos($_SERVER['REQUEST_URI'], '/events') !== false ? 'active' : ''); ?>" href="<?= $ShowEvents; ?>">Events</a>
</li>

虽然这对您的模板有点冗长,但您可能希望将逻辑分解为isActive()之类的函数。

答案 1 :(得分:0)

好的,对于我将来的参考(和其他人),我就是这样解决的。

1。制作两个函数

我在我的CMS的/ helpers /目录中创建了它,并将其命名为npe_nav.php(如果使用Concrete5 CMS,请不要将文件命名为navigation.php,因为该名称由c5占用,因此不起作用我)。

// Get URL segments
public function getURLSegments() {
    return explode("/", parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));
}

// Get a specific URL segment
// Takes a number which corisponds to a segment in the URL e.g. consider:
// http://www.domain.com/whats-on/show-name/events
// $navHelper->getURLSegment(1); will return whats-on
// $navHelper->getURLSegment(3); will return events
public function getURLSegment($n) {
    $segs = $this->getURLSegments();
    return count($segs) > 0 && count($segs) >= ($n-1)?$segs[$n]:'';
}

2。在模板中加载该功能

在Concrete5中,我像这样加载它(package-name指的是这个工具保存在CMS中的包):

// Load nav helper
$navHelper = Loader::helper('npe_nav','package-name');

3。在模板中调用该函数

对于网址:http://www.domain.com/whats-on/show-name/

这也会在应用.active之前检查第三段是否为空,因为此部分中的所有网址中都显示/whats-on/ - 所以不要让它在其他网页上处于活动状态。

<li>
    <a class="<?= (($navHelper->getURLSegment(1) == 'whats-on') && (is_null($navHelper->getURLSegment(3))) ? 'active' : ''); ?>" href="<?= $ShowWhatsOn; ?>">What's on</a>
</li>
对于网址:http://www.domain.com/whats-on/show-name/events

第3段的其他页面

<li>
    <a class="<?= ($navHelper->getURLSegment(3) == 'events' ? 'active' : ''); ?>" href="<?= $ShowEvents; ?>">Events</a>
</li>