Skip to content

Instantly share code, notes, and snippets.

@Pamblam
Created February 1, 2021 21:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Pamblam/d3cb8b770d03f54816f1594709b80c38 to your computer and use it in GitHub Desktop.
Save Pamblam/d3cb8b770d03f54816f1594709b80c38 to your computer and use it in GitHub Desktop.
parse paths in php
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