title: Echo the ending part or last folder of $_SERVER['DOCUMENT_ROOT'] in PHP
body: <p>I need to use <code>$_SERVER['DOCUMENT_ROOT'];</code> to scandir for files and folders to display for my nav menu.</p>
  
  <p>Let's say my root directory is at <code>/home/user/public_html/website/</code>.</p>
  
  <p>Here's how I echo the root directory:</p>
  
  <pre><code>echo $_SERVER['DOCUMENT_ROOT'];
  </code></pre>
  
  <p>it will display <code>/home/user/public_html/website/</code></p>
  
  <p>Here's how I echo a folder in the root directory:</p>
  
  <pre><code>echo $_SERVER['DOCUMENT_ROOT'].'about/';
  </code></pre>
  
  <p>it will display <code>/home/user/public_html/website/about/</code></p>
  
  <p><strong>Question:</strong> How can I strip everything that it displays all the way up to the root folder and/or sub-folder.</p>
  
  <p><strong>Example</strong>: If I echo <code>$_SERVER['DOCUMENT_ROOT']</code>, I want it to display as <code>/</code> instead of the entire <code>/home/user/public_html/website/</code> path.</p>
  
  <p>and if I echo a sub-folder I want it to display as <code>/about/</code> instead of <code>/home/user/public_html/website/about/</code>.</p>
  
  <p>So, how can I get it to echo just the ending part of the <code>$_SERVER['DOCUMENT_ROOT'];</code> instead of the entire directory path?</p>
  
  <p>I've tried <code>dirname</code> and <code>basename</code> but neither of those does what I need. I've thought of string replace but isn't there something much easier to add onto <code>$_SERVER['DOCUMENT_ROOT']</code> that will just echo out the root folder or root folder plus sub-folder?</p>
  
  <p><strong>Update</strong>:</p>
  
  <p>I ended up using the answer below from anant kumar singh but tweaking it using preg_split instead of explode because preg_split can take multiple string delimiters where as explode can take only 1.</p>
  
  <pre><code>$newArray = preg_split( " (-in/|-ca/|-co/) ", dirname($_SERVER['DOCUMENT_ROOT']) );
  if(count($newArray)&gt;1){
      echo '/'.$newArray[1].'/';
      }else{
          echo '/';
      }
  </code></pre>
  
  <p>If you know of a better way to accomplish what I'm trying to do, please post your answers below.</p>