Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - If URL contains string

Tags:

php

I am trying to check with PHP if the user is on some specific pages. Currently I am doing it like this:

<?php if($_SERVER['REQUEST_URI'] == "/forum/"){echo "class='active'";} ?>

Although, this only works if the URL is http://example.com/forum/

How can I make the above code works, on both /forum/ but also on /forum/??

Example:

http://example.com/forum/anotherpage
like image 371
oliverbj Avatar asked Oct 12 '25 08:10

oliverbj


1 Answers

You can use a startswith function (see this stackoverflow post: startsWith() and endsWith() functions in PHP). Here, you test would be:

if (startsWith ($_SERVER['REQUEST_URI'], '/forum/'))

You can also use a regexp: http://php.net/manual/en/regex.examples.php. Here, your test would be:

if (preg_match ('#^/forum/#', $_SERVER['REQUEST_URI']))

Hope this helps.

like image 64
Niols Avatar answered Oct 14 '25 22:10

Niols