Search code examples
phpdirectory-structure

how do you extract the root directory?


I am still learning php.

'SCRIPT_FILENAME' => string 'D:/Project Storage/wnmp/www/folder/index.php' (length=45)
'SCRIPT_NAME'     => string '/folder/index.php' (length=18)
'DOCUMENT_URI'    => string '/folder/index.php' (length=18)
'PHP_SELF'        => string '/folder/index.php' (length=18)
'REQUEST_URI'     => string '/folder/helloworld/helloworldtwo/etc' (length=15)

as you can see i just want to get the helloworld/helloworldtwo/etc

any idea to extract the folder ? so it will be helloworld/helloworldtwo/etc ?

what im thinking is im defining my folder like $root = 'folder'. then i extract it if it match, but the problem is with what ?

the second idea is to get from php_self or anything above to get the first from /first/second.php, but again i dont know the best way to do it.

and another problem is when we have like two folders in the front ? btw thanks for all of the replay, im still doing some read php.net, test, and try.

'SCRIPT_FILENAME' => string 'D:/Project Storage/wnmp/www/folder/index.php' (length=45)
'SCRIPT_NAME'     => string '/folder/folder2/index.php' (length=18)
'DOCUMENT_URI'    => string '/folder/folder2/index.php' (length=18)
'PHP_SELF'        => string '/folder/folder2/index.php' (length=18)
'REQUEST_URI'     => string '/folder/folder2/helloworld/helloworldtwo/etc' (length=15)

the question is still the same how can i get the helloworld/hellowrodltwo/etc the right way.

edit* guys thanks a lot i have made a solution

$str = 'folder/folder/helloworld/helloworldtwo/etc';
$folder = 'folder/folder';
$q = str_replace($folder, NULL, $str);
echo $q;

but if there is anything / alternative or a better way to do it please do.

Thanks again.


Solution

  • You can use the explode function in PHP

    $str = 'folder/helloworld/helloworldtwo/etc';
    
    print_r(explode('/', $str, 2));
    

    The output will be:

    Array
    (
        [0] => folder
        [1] => helloworld/helloworldtwo/etc
    )
    

    If you have multiple folder/ you can do use 'folder/' as the delimiter and don't impose a limit

    $str = 'folder/folder/helloworld/helloworldtwo/etc';
    
    print_r(explode('folder/', $str));
    

    The output will be:

    array (
      0 => '',
      1 => '',
      2 => 'helloworld/helloworldtwo/etc',
    )
    

    then you can use the implode function to join it back into a string

    $returnValue = implode('', array (
      0 => '',
      1 => '',
      2 => 'helloworld/helloworldtwo/etc',
    ));
    

    Joining this 2 functions you can remove how many folders you want from the url and have the clean url at the end in a string