1

I'm using the following code to set the active state in my menu:

<li class="<?php echo basename($_SERVER['PHP_SELF']) == 'index.php' ? 'active' : '';?>">
<a href="index.php">Home</a></li>
<li class="<?php echo basename($_SERVER['PHP_SELF']) == 'projects.php' ? 'active' : '';?>">
<a href="projects.php">Projects</a></li>

And It works fine for the specific url such as projects.php, but also we had the following "projects" and we want to set the active state in the menu for them:

  • project-client-name.php
  • project-client-name-2.php
  • project-client-name-3.php

Is there any alternative to set the active state to a url who it begins or contains "project" in the url, in this way it works for project-client-name.php and projects.php:

<?php echo basename($_SERVER['PHP_SELF']) == 'project' ? 'active' : '';?>

Thanks in advance.

  • Possible duplicate of [How do I check if a string contains a specific word?](https://stackoverflow.com/questions/4366730/how-do-i-check-if-a-string-contains-a-specific-word) – Cid Sep 16 '19 at 08:36

2 Answers2

0

Despite the fact that it's a weird solution, you could use strpos() or preg_match()

<?php echo strpos(basename($_SERVER['PHP_SELF']), 'project') !== FALSE ? 'active' : '';?>

strpos looks for first occurence of substring and returns it's int position or FALSE if it's not found

Robert
  • 19,800
  • 5
  • 55
  • 85
0

The following code works for me:

<?php echo preg_match("/^(project){1}(.){0,}\w+/", basename($_SERVER['PHP_SELF'])) ? 'active' : ''; ?>

Thanks!