Skip to content

Instantly share code, notes, and snippets.

@yokotak0527
Last active February 12, 2016 11:55
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 yokotak0527/cd9c5318591cbc242cd1 to your computer and use it in GitHub Desktop.
Save yokotak0527/cd9c5318591cbc242cd1 to your computer and use it in GitHub Desktop.
class Path{
private static function encode_special_text($path){
$path = str_replace(':/','{{ptcl_sep}}',$path);
return $path;
}
private static function decode_special_text($path){
$path = str_replace('{{ptcl_sep}}',':/',$path);
return $path;
}
// =========================================================================
// 結合
// =========================================================================
public static function join(){
$opt = [
'last_slash' => 'true'
];
$args = func_get_args();
// オプション変更
if(is_array(end($args))) $opt = array_merge($opt,array_pop($args));
// ---------------------------------------------------------------------
$path = trim($args[0]);
// 先頭
if(preg_match('/^\/{2}/',$path)) $path = preg_replace('/^\/{2}/','//',$path);
else $path = preg_replace('/^\/+/','/',$path);
// 末尾
if(preg_match('/[a-zA-Z]:\/{2}$/',$path)) $path = preg_replace('/\/+$/','/',$path);
else $path = preg_replace('/\/+$/','',$path);
$path = Path::encode_special_text($path);
$i = 1;
$l = count($args);
for(; $i<$l; $i++){
$base_arr = explode( '/', $path );
$path_arr = explode( '/', preg_replace( '/^\/+|\/+$/', '', trim($args[$i]) ) );
$ii = 0;
$ll = count($path_arr);
for(; $ii<$ll; $ii++){
if(preg_match('/^\.{2}$/',$path_arr[$ii])) array_pop($base_arr);
else if(preg_match('/^\.$/',$path_arr[$ii])) continue;
else $base_arr[] = $path_arr[$ii];
}
$path = implode('/',$base_arr);
}
$path = Path::decode_special_text($path);
if($opt['last_slash'] && !preg_match('/\.[a-zA-Z]{2,4}\??[a-zA-Z0-9\-=_\.\[\]\~\+\-\\|\¥\)\(\#\!\'\"\}\{\@\$%&\^`\*\;\:]*$/',$path)){
$path .= '/';
}
return $path;
}
// =========================================================================
// パスの最後の要素を返す
// =========================================================================
public static function basename($p='',$ext=''){
$p = explode('/',$p);
$p = end($p);
if(!empty($ext)){
$ext = '.'.$ext;
$p = substr($p,0,strpos($p,$ext));
return $p;
}else return $p;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment