I need to use $_SERVER['DOCUMENT_ROOT'];
to scandir for files and folders to display for my nav menu.
Let's say my root directory is at /home/user/public_html/website/
.
Here's how I echo the root directory:
echo $_SERVER['DOCUMENT_ROOT'];
it will display /home/user/public_html/website/
Here's how I echo a folder in the root directory:
echo $_SERVER['DOCUMENT_ROOT'].'about/';
it will display /home/user/public_html/website/about/
Question: How can I strip everything that it displays all the way up to the root folder and/or sub-folder.
Example: If I echo $_SERVER['DOCUMENT_ROOT']
, I want it to display as /
instead of the entire /home/user/public_html/website/
path.
and if I echo a sub-folder I want it to display as /about/
instead of /home/user/public_html/website/about/
.
So, how can I get it to echo just the ending part of the $_SERVER['DOCUMENT_ROOT'];
instead of the entire directory path?
I've tried dirname
and basename
but neither of those does what I need. I've thought of string replace but isn't there something much easier to add onto $_SERVER['DOCUMENT_ROOT']
that will just echo out the root folder or root folder plus sub-folder?
Update:
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.
$newArray = preg_split( " (-in/|-ca/|-co/) ", dirname($_SERVER['DOCUMENT_ROOT']) );
if(count($newArray)>1){
echo '/'.$newArray[1].'/';
}else{
echo '/';
}
If you know of a better way to accomplish what I'm trying to do, please post your answers below.
You can go with explode in the following manner:--
$newArray = explode('website/',$_SERVER['DOCUMENT_ROOT']);
if(count($newArray)>1){
echo "/".$newArray[1];
}else{
echo '/';
}
As you already said that preg_split is done the job for you:-
$newArray = preg_split( " (-in/|-ca/|-co/) ", dirname($_SERVER['DOCUMENT_ROOT']) ); if(count($newArray)>1){ echo "/".$newArray[1]."/"; }else{ echo '/'; }
NOTE:- Don't be panic.I am not going to take your credit. I just did it for the future peoples purpose. If you put it as an answer then i will remove it.