2

Warning - I'm a front end designer; Please pardon my fumbling of the PHP concepts here

So I've got a PHP statement that basically outputs a class in my markup when the URL of the page matches the statement. Here it is:

<?php if (strpos($_SERVER["REQUEST_URI"],"/technology") === false) {} else { echo "current"; } ?>

As is, I'm using the statement inside a class attribute on an <a> tag inside of a <nav> element to add a class of "current" so that I can style that nav element differently for the page your currently on. As is, it works fine for the site main navigation, because it returns as true even for pages deeper than just /technology, such as /technology/security which is what I want for the sitewide nav.

The problem is I'd like to use a similar but modified version of this code on subsection navigations that will only appear on the main subpage categories.

So in those cases, I only want the result to be true when the exact URL is matched. More specifically, I want to exclude the parent (ie. /technology) even when I'm on /technology/security.

So how can I modify the statement to evaluate that way?

Joel Glovier
  • 7,469
  • 9
  • 51
  • 86
  • Have you looked at regular expression? http://webcheatsheet.com/php/regular_expressions.php – Araw Mar 21 '12 at 19:47
  • 1
    You should probably have a talk with a backend developer / get some basic content management in there that can handle the request info and generate a menu based on a page structure and tell you which on it's on right now... (using regexes and the REQUEST_URI only goes so far) – sg3s Mar 21 '12 at 20:55
  • Yes, but regex is beyond my experience and scope for this project. Also, I'm using Wordpress on this, and I forgot that WP has a feature for this. DOLP!! Except I'm still not sure it will work for my solution since I'm not planning on adding the subnavs into the Wordpress menus function...but I may have to. – Joel Glovier Mar 22 '12 at 01:38

2 Answers2

4

The preg_match function will work much better here, because regular expressions let you match the end of the string using the $ operator.

<?php
if(preg_match("%/technology$%", $_SERVER['REQUEST_URI'])){
    echo "current";
}
?>
nkorth
  • 1,684
  • 1
  • 12
  • 28
1

Sorry, but that empty if is bugging me, you should re-write it to:

<?php if (strpos($_SERVER["REQUEST_URI"],"/technology") !== false) { echo "current"; } ?>
Mike Purcell
  • 19,847
  • 10
  • 52
  • 89