Skip to content

Instantly share code, notes, and snippets.

@yokotak0527 yokotak0527/php path
Last active Feb 12, 2016

Embed
What would you like to do?
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
You can’t perform that action at this time.