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;
@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