Skip to content

Instantly share code, notes, and snippets.

@TheRealJAG
Last active September 23, 2019 02:06
Show Gist options
  • Save TheRealJAG/0acc8b81be8012f14a6b58808a0de26d to your computer and use it in GitHub Desktop.
Save TheRealJAG/0acc8b81be8012f14a6b58808a0de26d to your computer and use it in GitHub Desktop.
Write a function that provides change directory (cd) function for an abstract file system.
<?php
class Path {
public $currentPath;
function __construct($path) {
$this->currentPath = $path;
}
public function cd($newPath) {
$innerCounter = 0;
$strOut= '';
$newPath = explode('/',$newPath);
$oldPath = explode('/', $this->currentPath);
foreach($newPath as $str) {
echo $str.'<P>';
if($str == '..') $innerCounter++;
}
$oldLength = count($oldPath);
for($i=0;$i<($oldLength - $innerCounter);$i++)
$strOut .= $oldPath[$i]."/";
$newLength = count($newPath);
for($i=0;$i<$newLength;$i++){
if($newPath[$i] !='..'){
$strOut = $strOut.$newPath[$i].'';
}
}
$this->currentPath = $strOut;
return $this;
}
}
$path = new Path('/a/b/c/d');
echo $path->cd('../x')->currentPath;
@zachary0303
Copy link

`
class Path
{
public $currentPath;

function __construct($path)
{
    $this->currentPath = $path;
}

public function cd($newPath)
{
    $dirs = explode('/', $this->currentPath);
    $new_dirs = explode('/', $newPath);
    
    $new_path = [];
    
    foreach ($new_dirs as $new_dir) {
        if ($new_dir === '..') {
            array_pop($dirs);
        } else {
            $new_path[] = $new_dir;
        }
    }
            
    $new_path = array_merge($dirs, $new_path);
    
    $this->currentPath = implode('/', $new_path);
    
}

}

$path = new Path('/a/b/c/d');
$path->cd('../x');
echo $path->currentPath;
`

@SuperStar518
Copy link

I think this might be an approved answer.

https://github.com/alidavid0418/php-path-testdome

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment