Here's a puzzler. I have a variable that contains computer file paths. I need to separate the filename from the path.
Example: From this:
$filepath = C:\\User\Me\Myfiles\file.jpg
I need this:
$path = C:\\User\Me\Myfiles\
$file = file.jpg
I know how to get the substrings of $filepath using subs开发者_运维知识库tr. The problem is using "\" as a "needle" to get the position of the filename.
This causes an error:
$pos = strrpos("\",$filepath);
This doesn't cause an error, but doesn't give me a value for $pos:
$pos = strrpos("\\",$filepath);
As always, any help with be rewared with my eternal gratitude.
$pos = strrpos("\\",$filepath);
This is trying to find the position of $filepath
in the string "\\"
. Unless the $filepath
is a single backslash, no position will be returned.
You want to swap the two arguments around.
$pos = strrpos($filepath, "\\");
Also, basename($filepath)
or pathinfo($filepath, PATHINFO_BASENAME)
can be used to get the file name.
Look at the output of pathinfo($filepath)
, or for an oo approach, at the available methods of SplFileInfo
.
preg_match('#^(.+)\\\\(.+)$#', $filepath, $matches);
$path = $matches[1];
$file = $matches[2];
This works because the +
regex quantifier is greedy, so it will match all the characters it can. The \
is double-escaped, once for the PHP string, and once for the regex.
精彩评论