Created
February 1, 2021 21:47
-
-
Save Pamblam/d3cb8b770d03f54816f1594709b80c38 to your computer and use it in GitHub Desktop.
parse paths in php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class fpParser{ | |
public $path; | |
public $basename; | |
public $basename_noext; | |
public $basename_noext_noiteration; | |
public $extention; | |
public $directory_sep; | |
public $dir_tree; | |
public $iteration; | |
public function __construct($path, $directory_sep = '/'){ | |
$this->directory_sep = $directory_sep; | |
$this->path = $path; | |
$this->parsePath(); | |
} | |
private function parsePath(){ | |
$path_parts = explode($this->directory_sep, $this->path); | |
if(empty($path_parts)) throw new Error("What you talkin' 'bout, Willis?"); | |
$this->basename = array_pop($path_parts); | |
$this->dir_tree = $path_parts; | |
if(substr($this->basename, 0, 1) === '.'){ | |
$this->basename_noext = $this->basename; | |
}else{ | |
$name_parts = explode(".", $this->basename, 2); | |
$this->basename_noext = array_shift($name_parts); | |
if(!empty($name_parts)){ | |
$this->extention = array_shift($name_parts); | |
} | |
} | |
preg_match('/.*\_(\d+)$/', $this->basename_noext, $matches); | |
if(!empty($matches)){ | |
$strlen = strlen($this->basename_noext) - (strlen($matches[1]) + 1); | |
$this->basename_noext_noiteration = substr($this->basename_noext, 0, $strlen); | |
$this->iteration = intval($matches[1]); | |
}else{ | |
$this->basename_noext_noiteration = $this->basename_noext; | |
} | |
} | |
private function rebuildPath(){ | |
$path = ''; | |
if(!empty($this->dir_tree)){ | |
$path .= implode($this->directory_sep, $this->dir_tree); | |
$path .= $this->directory_sep; | |
} | |
$path .= $this->basename_noext_noiteration; | |
if(!empty($this->iteration)){ | |
$path .= "_" . $this->iteration; | |
} | |
if(!empty($this->extention)){ | |
$path .= "." . $this->extention; | |
} | |
$this->path = $path; | |
$this->parsePath(); | |
} | |
public static function sanitizeBasename($basename){ | |
return preg_replace('/[^a-zA-Z0-9\-\_\.]+/', '_', $basename); | |
} | |
public function iterate(){ | |
if(empty($this->iteration)) $this->iteration = 0; | |
$this->iteration++; | |
$this->rebuildPath(); | |
} | |
} | |
$basename = fpParser::sanitizeBasename("asdf3$@%$^#$%^@#452345345433.po.pop"); | |
$parser = new fpParser($basename); | |
echo $parser->path . "\n"; | |
$parser->iterate(); | |
echo $parser->path . "\n"; | |
$parser->iterate(); | |
echo $parser->path . "\n"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment