basename php 中文,basename - [ php中文手册 ] - 在线原生手册 - php中文网

用户评论:

[#1]

Anonymous [2014-12-15 14:30:57]

As already pointed out above, if a query string contains a '/' character, basename will not handle it well. But it can come really handy when you want to pass a url with query string to a funtion that copies/downloads the file using basename as local filename, by attaching  an extra query to the end of the url:

$url='http://example.com/url?with=query_string';basename($url);// url?with=query_string$url=$url.'&filename_for_basename=/desired_filename.ext';basename($url);// desired_filename.ext?>

Note: you can use the filename from the HTTP header (if present) to get the file with it's original filename.

[#2]

poop at poop dot com [2014-11-22 00:42:02]

@ lcvalentine at gmail dot com

>This is much simpler:

>$ext = strrchr( $filename, '.' );

Even though yours is shorter, you can also do:

$ext = end(explode(".", basename($file

[#3]

lcvalentine at gmail dot com [2014-11-21 16:32:16]

@softontherocks at gmail dot com

> If you want to get the extension of a file, I posted a function in

> http://softontherocks.blogspot.com/2013/07/obtener-la-extension-de-un-fichero-con.html

>

> The function is:

>

> function getExtension($file) {

>   $pos = strrpos($file, '.');

>   return substr($file, $pos+1);

> }

This is much simpler:

$ext = strrchr( $filename, '.' );

[#4]

softontherocks at gmail dot com [2014-10-31 18:38:25]

If you want to get the extension of a file, I posted a function in http://softontherocks.blogspot.com/2013/07/obtener-la-extension-de-un-fichero-con.html

The function is:

function getExtension($file) {

$pos = strrpos($file, '.');

return substr($file, $pos+1);

}

[#5]

Muhammad El-Saeed muhammad at elsaeed dot info [2013-04-19 04:58:47]

to get the base url of my website

function url(){

$base_url = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off' ? 'https' : 'http';

$base_url .= '://'. $_SERVER['HTTP_HOST'];

$base_url .= str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']);

return $base_url;

}

[#6]

leaksin [ at ] gmail [ dot ] com [2012-12-14 18:53:27]

This is a string function,too.

basename() does not check the current path for being exist or not.

It's great to use it for working with URL or search implement.

[#7]

swedish boy [2009-10-12 15:43:36]

Here is a quick way of fetching only the filename (without extension) regardless of what suffix the file has.

echo$file_name;// outputs 'image'?>

[#8]

hello at haroonahmad dot co dot uk [2008-09-18 08:13:51]

I got a blank output from this code

$cur_dir = basename(dirname($_SERVER[PHP_SELF]))

suggested earlier by a friend here.

So anybody who wants to get the current directory path can use another technique that I use as

//suppose you're using this in pageitself.php page

$current_dir=dirname(realpath("pageitself.php"));

I hope it helps.

[#9]

zandor_zz at yahoo dot it [2008-09-08 01:34:46]

It might be useful to have a version of the function basename working with arrays too.

{$onlyfilename=end(explode("/",$file) );

if(is_string($exts) )

{

if (strpos($onlyfilename,$exts,0) !==false)$onlyfilename=str_replace($exts,"",$onlyfilename);

}

else if (is_array($exts) )

{// works with PHP version <= 5.x.xforeach($extsas$KEY=>$ext)

{$onlyfilename=str_replace($ext,"",$onlyfilename);

}

}

return$onlyfilename;

}?>

[#10]

(remove) dot nasretdinov at (remove) dot gmail dot com [2008-08-27 08:20:20]

There is only one variant that works in my case for my Russian UTF-8 letters:

function mb_basename($file)

{

return end(explode('/',$file));

}

><

It is intented for UNIX servers

[#11]

pai dot ravi at yahoo dot com [2008-08-15 08:44:12]

once you have extracted the basename from the full path and want to separate the extension from the file name, the following function will do it efficiently:

{$pos=strrpos($filename,'.');

if ($pos===false)

{// dot is not found in the filenamereturn array($filename,'');// no extension}

else

{$basename=substr($filename,0,$pos);$extension=substr($filename,$pos+1);

return array($basename,$extension);

}

}?>

[#12]

adrian at foeder dot de [2007-12-20 00:33:43]

On windows systems, filenames are case-insensitive. If you have to make sure the right case is used when you port your application to an unix system, you may use a combination of the following:

basename itself does not check the filesystem for the given file, it does, so it seems, only string-manipulation.

With realpath() you can "extend" this functionality.

[#13]

stephane dot fidanza at gmail dot com [2007-04-11 04:33:50]

Support of the $suffix parameter has changed between PHP4 and PHP5:

in PHP4, $suffix is removed first, and then the core basename is applied.

conversely, in PHP5, $suffix is removed AFTER applying core basename.

Example:

$file="path/to/file.xml#xpointer(/Texture)";

echobasename($file,".xml#xpointer(/Texture)");?>

Result in PHP4: file

Result in PHP5: Texture)

[#14]

thoughts at highermind dot org [2007-01-30 05:45:35]

Basename without query string:

$filename=array_shift(explode('?',basename($url_path)));?>

[#15]

lazy lester [2006-02-17 16:19:19]

If your path has a query string appended, and if the query string contains a "/" character, then the suggestions for extracting the filename offered below don't work.

For instance if the path is like this:

http://www.ex.com/getdat.php?dep=n/a&title=boss

Then both the php basename() function, and also

the $_SERVER[QUERY_STRING] variables get confused.

In such a case, use:

$path_with_query="http://www.ex.com/getdat.php?dep=n/a&title=boss";$path=explode("?",$path_with_query);$filename=basename($path[0]);$query=$path[1];?>

[#16]

[2005-11-15 04:57:08]

icewinds exmaple wouldn't work, the query part would contain the second char of the filename, not the query part of the url.

$file="path/file.php?var=foo";$file=explode("?",basename($file));$query=$file[1];$file=$file[0];?>

That works better.

[#17]

icewind [2005-11-02 00:44:39]

Because of filename() gets "file.php?var=foo", i use explode in addition to basename like here:

$file = "path/file.php?var=foo";

$file = explode("?", basename($file));

$file = $file[0];

$query = $file[1];

Now $file only contains "file.php" and $query contains the query-string (in this case "var=foo").

[#18]

www.turigeza.com [2005-10-24 12:47:04]

simple but not said in the above examples

echo basename('somewhere.com/filename.php?id=2', '.php');

will output

filename.php?id=2

which is not the filename in case you expect!

[#19]

crash at subsection dot org dot uk [2005-09-22 12:38:51]

A simple way to return the current directory:

$cur_dir = basename(dirname($_SERVER[PHP_SELF]))

since basename always treats a path as a path to a file, e.g.

/var/www/site/foo/ indicates /var/www/site as the path to file

foo

[#20]

pvollma at pcvsoftware dot net [2005-07-14 09:28:18]

Note that in my example below, I used the stripslashes function on the target string first because I was dealing with the POST array $_FILES. When creating this array, PHP will add slashes to any slashes it finds in the string, so these must be stripped out first before processing the file path. Then again, the only reason I can think of that basename() would fail is when dealing with Windows paths on a *nix server -- and the file upload via POST is the only situation I can think of that would require this. Obviously, if you are not dealing with these additional slashes, invoking stripslashes() first would remove the very separators you need extract the file name from the full path.

[#21]

amitabh at NOSPAM dot saysnetsoft dot com [2005-07-14 01:55:55]

The previous example posted by "pvollma" didn't work out for me, so I modified it slightly:

{$newfile=basename($file_name);

if (strpos($newfile,'\\') !==false)

{$tmp=preg_split("[\\\]",$newfile);$newfile=$tmp[count($tmp) -1];

return($newfile);

}

else

{

return($file_name);

}

}?>

[#22]

pvollma at pcvsoftware dot net [2005-07-13 11:43:52]

There is a real problem when using this function on *nix servers, since it does not handle Windows paths (using the \ as a separator). Why would this be an issue on *nix servers? What if you need to handle file uploads from MS IE? In fact, the manual section "Handling file uploads" uses basename() in an example, but this will NOT extract the file name from a Windows path such as C:\My Documents\My Name\filename.ext. After much frustrated coding, here is how I handled it (might not be the best, but it works):

$filen=stripslashes($_FILES['userfile']['name']);$newfile=basename($filen);

if (strpos($newfile,'\\') !==false) {$tmp=preg_split("[\\\]",$newfile);$newfile=$tmp[count($tmp) -1];

}?>

$newfile will now contain only the file name and extension, even if the POSTed file name included a full Windows path.

[#23]

KOmaSHOOTER at gmx dot de [2005-01-30 06:18:28]

if you want the name of the parent directory

$_parenDir_path=join(array_slice(split("/",dirname($_SERVER['PHP_SELF'])),0,-1),"/").'/';// returns the full path to the parent dir$_parenDir=basename($_parenDir_path,"/");// returns only the name of the parent dir

// or$_parenDir2=array_pop(array_slice(split("/",dirname($_SERVER['PHP_SELF'])),0,-1));// returns also only the name of the parent direcho('$_parenDir_path  = '.$_parenDir_path.'
');

echo('$_parenDir  = '.$_parenDir.'
');

echo('$_parenDir2  = '.$_parenDir2.'
');?>

[#24]

KOmaSHOOTER at gmx dot de [2005-01-29 16:24:16]

If you want the current path where youre file is and not the full path then use this :)

Example:

www dir: domain.com/temp/2005/january/t1.php

<?phpecho ('dirname 
'.dirname($_SERVER['PHP_SELF']).'
');// returns: /temp/2005/january?>

if you combine these two you get this

And for the full path use this

<?phpecho (' PHP_SELF 
'.$_SERVER['PHP_SELF'].'
');// returns: /temp/2005/january/t1.php?>

[#25]

KOmaSHOOTER at gmx dot de [2003-11-28 02:33:45]

Exmaple for exploding ;) the filename to an array

<?phpecho (basename($PHP_SELF)."
");// returnes filename.php$file=basename($PHP_SELF);$file=explode(".",$file);print_r($file);// returnes Array ( [0] => filename [1] => php )echo("
");$filename=basename(strval($file[0]),$file[1]);

echo($filename."
");// returnes  filenameecho(basename($PHP_SELF,".php")."
");// returnes  filenameecho("
");

echo("
");//show_source(basename ($PHP_SELF,".php").".php")show_source($file[0].".".$file[1])?>

[#26]

giovanni at giacobbi dot net [2003-11-08 07:52:58]

No comments here seems to take care about UNIX system files, which typically start with a dot, but they are not "extensions-only".

The following function should work with every file path. If not, please let me know at my email address.

function remove_ext($str) {

$noext = preg_replace('/(.+)\..*$/', '$1', $str);

print "input: $str\n";

print "output: $noext\n\n";

}

remove_ext("/home/joh.nny/test.php");

remove_ext("home/johnny/test.php");

remove_ext("weirdfile.");

remove_ext(".hiddenfile");

remove_ext("../johnny.conf");

[#27]

daijoubu_NOSP at M_videotron dot ca [2003-10-15 22:22:13]

An faster alternative to:

array_pop(explode('.',$fpath));?>

would be:

substr($fpath,strrpos($fpath,'.'));// returns the dot?>

If you don't want the dot, simply adds 1 to the position

substr($fpath,strrpos($fpath,'.') +1);// returns the ext only?>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值