开发者

Truncating a string from last till a character is encountered in PHP

I have a string with a path like so:

C:/myfolder/mysubfolder/myfile.doc

I need to truncate the string to become:

myfile.doc

Needless to say, I have a list of such paths with different lengths and different folder depths. What I need is something like trancating the rest of the string beginning from the last of the string till the first / is encou开发者_如何学编程ntered.

How can I achieve this in PHP.

Many thanks


$path = 'C:/myfolder/mysubfolder/myfile.doc':
$filename = basename($path);
echo $filename; // "myfile.doc"

See Manual "basename()". For more detailed information about a path see pathinfo()


You can use the basename() function for this.

echo basename("C:/myfolder/mysubfolder/myfile.doc");

Output:

myfile.doc

Note that this doesn't exactly do what you described, because for these inputs:

/etc/
.

it would return

etc
.

So an (untested) alternative could be:

$fullname = "C:/myfolder/mysubfolder/myfile.doc";
$parts = explode("/", $fullname);
$filename = $parts[count($parts)-1];
echo $filename;


If you mean you want the filename segment, you can use basename()

http://php.net/manual/en/function.basename.php

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜