fire specialist
fire specialist

Reputation: 1

How to have class="selected" on same element with 2 different urls

As the title says.

I have this piece of code:

(strpos(htmlspecialchars($_SERVER['REQUEST_URI']), 'forum')) ? 'class="selected' : '';

Now this code has the element selected if the url is mysite.com/forum. But I wanna select the same element if the url is mysite.com/thread too.

I have tried:

(strpos(htmlspecialchars($_SERVER['REQUEST_URI']), 'forum' || 'thread')) ? 'class="selected' : '';

But then neither work, I get no error messages. What am I doing wrong?

Upvotes: 0

Views: 40

Answers (3)

steveteuber
steveteuber

Reputation: 182

Try this:

<?php if (preg_match('#^/(forum|thread)#', $_SERVER['REQUEST_URI'])) echo 'class="selected"'; ?>

Upvotes: 0

Halcyon
Halcyon

Reputation: 57703

The expression 'forum' || 'thread' evaluates to true because non empty strings are truthy.

So your full expression becomes:

strpos(htmlspecialchars($_SERVER['REQUEST_URI']), true)

It's possible that true will be cast to a string because strpos wants a string. Which changes it to:

strpos(htmlspecialchars($_SERVER['REQUEST_URI']), "1")

The expressions you're looking for is:

strpos(htmlspecialchars($_SERVER['REQUEST_URI']), "forum") || strpos(htmlspecialchars($_SERVER['REQUEST_URI']), "thread")

This can still be improved: htmlspecialchars is not needed here and strpos can return 0 (which is falsy), so:

strpos($_SERVER['REQUEST_URI'], "forum") !== false || strpos($_SERVER['REQUEST_URI'], "thread") !== false 

Upvotes: 1

H&#252;seyin BABAL
H&#252;seyin BABAL

Reputation: 15550

You can use this;

$contextPath = htmlspecialchars($_SERVER['REQUEST_URI']);

(strpos($contextPath, 'forum') || strpos(contextPath, 'thread')) ? 'class="selected' : '';

Upvotes: 0

Related Questions