michaelmcgurk
michaelmcgurk

Reputation: 6509

Grab portion of URL with PHP

I have the following PHP to grab a part of the URL.

I have a URL www.mysite.com/my-team2.php and it echoes my team instead of my team2.

$page = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if (strpos(strtolower($page),'my-team') !== false) {
    echo 'my team';
} elseif (strpos(strtolower($page),'my-team2') !== false) {
    echo 'my team2';
}

Why is this?

Upvotes: 0

Views: 49

Answers (4)

LF-DevJourney
LF-DevJourney

Reputation: 28529

You should put the most specific match in the first

echo strpos(strtolower($page),'my-team2') !== false ? 'my-team2' : strpos(strtolower($page),'my-team2') !== false ? 'my-team' : '';

Upvotes: 0

kenarsuleyman
kenarsuleyman

Reputation: 1020

Because "my-team" is substring of "my-team2". It's better to use regular expressions on these kind of situtaions.

Upvotes: 1

sidyll
sidyll

Reputation: 59287

That's because my-team is contained in my-team2, so the first test is already true.

Either reverse them (rather simplistic) or use another approach, such as comparing the whole string or using a regular expression match.

Upvotes: 1

user3005775
user3005775

Reputation: 306

this is because it is finding the first instance first, the else if will never occur, what you should do is swap them

if (strpos(strtolower($page),'my-team2') !== false) {
echo 'my team2';
} elseif (strpos(strtolower($page),'my-team') !== false) {
echo 'my team';
}

so basically what it was doing without swapping them was finding the text 'my-team'

since the text 'my-team'is part of the text 'my-team2', it would always trigger the if without ever seeing the else if, because the if would always == TRUE.

by swapping them and putting the 2 first, 'my-team2' it will have to find that first, thus if the 2 is not in it, then the else if will trigger

Upvotes: 4

Related Questions