tags:

views:

37

answers:

3

Hi,

basically if I have a string like this:

$str = \data1\data2\data3\data_tmp\file.pgp

can anyone tell me how to get the last part 'file.pgp'?

TIA.

+4  A: 
$last = array_pop(explode('\\', $str));

You don't need foreach for that. It's used when you have to iterate through the whole collection (in your case, array).

If you need to get the remaining part of the string:

$segments = explode('\\', $str);
$last = array_pop($segments);

It will be in $segments, as an array. If you want to convert it back to a string, then use join('\\', $segments). However, if this is a Windows path and you're running PHP on Windows, then you should be using the basename and dirname functions.

Ignas R
thank you. can you tell me is there any way to get the remaining bit excluding the last bit?
JPro
Works well according to http://codepad.org/XjiPZWeu .
Tchalvak
+6  A: 

You are looking for the basename() function.

This function takes a file path and returns the file name without the suffix (the final part of your file name that specifies its type)

Sean Vieira
basename does not seems to work for my requirement
JPro
Interestingly, seems like that's only going to work in a windows environment, as per here:http://codepad.org/XjiPZWeu
Tchalvak
@Tchalvak, that behavior is actually documented in the PHP documentation: http://www.php.net/manual/en/function.basename.php
Ignas R
Yep, environment dependent.
Tchalvak
It will work in other environments, but only if the normal system separator is used. See: http://codepad.org/dLIPlp2R and this quote from the php manual: "On Windows, both slash (/) and backslash (\) are used as directory separator character. In other environments, it is the forward slash (/)."
Sean Vieira
@Ignas R ... Thanks! (Sorry for posting the same information, I didn't see your comment until after I had posted mine.
Sean Vieira
A: 

perhaps pathinfo() will give you what you need

if that doesn't do it try

$path = str_replace('\\', '/', $path)

first

Scott Evernden