Search code examples
phpregexstringdrupaldrupal-7

PHP match string parent level URL string only. Ignore sub-directory paths


I'm looking to implement a simple conditional within a template file (Drupal 7) that checks the URL path and only operates on the condition when the string is exact/page is the parent. At the moment, I have a conditional working, but the condition still executes for sub pages of the URL string when matched. E.g:

$url_vars = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if (strpos($url_vars, 'parent-page') !== false) {
// Do something
}

This still operates for anything hierarchical, so:

parent-page/sub-page

How do I make this work so that the condition strictly manages the parent directory only and not the sub-directory? Any guidance or ideas would be of great help. I'd prefer to handle this server-side, and not on the front-end.

Thanks! Mark.


Solution

  • I am not exactly sure how much your REQUEST_URI string will vary, but this may suffice:

    if(strpos($_SERVER['REQUEST_URI'],'parent-page')!==false && strpos($_SERVER['REQUEST_URI'],'parent-page/')===false){
    

    This just checks that the parent_page (static string) exists in the REQUEST_URI and that it DOES NOT have a trailing /

    If this doesn't do the trick, please offer more specific details about your URI values.

    A potentially useful reference: https://stackoverflow.com/a/4731027/2943403