Remove unnecessary slashes from path

后端 未结 6 532
温柔的废话
温柔的废话 2021-02-06 08:00
$path = \'/home/to//my///site\';

I am trying to remove unnecessary forward slashes / from the path above

I am trying to get this

6条回答
  •  青春惊慌失措
    2021-02-06 08:51

    It replaces (consecutive) occurences of / and \ with whatever is in DIRECTORY_SEPARATOR, and processes /. and /.. fine. Paths returned by get_absolute_path() contain no (back)slash at position 0 (beginning of the string) or position -1 (ending)

    function get_absolute_path($path) {
        $path = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $path);
        $parts = array_filter(explode(DIRECTORY_SEPARATOR, $path), 'strlen');
        $absolutes = array();
        foreach ($parts as $part) {
            if ('.' == $part) continue;
            if ('..' == $part) {
                array_pop($absolutes);
            } else {
                $absolutes[] = $part;
            }
        }
        return implode(DIRECTORY_SEPARATOR, $absolutes);
    }
    

    A test:

    var_dump(get_absolute_path('this/is/../a/./test/.///is'));
    

    Returns: string(14) "this/a/test/is"

提交回复
热议问题