Reputation: 9034
I have done my research before posting, but cannot find an answer to this. How do I get the portion of a string after a certain character?
For example, for the string:
gallery/user/profile/img_904.jpg
I want to return:
img_904.jpg
I am also concerned about bugs with basename()
regarding UTF-8 filenames containing Asian characters.
Upvotes: 3
Views: 90
Reputation: 24709
In this case, you can just use the basename()
function:
php > $path = 'gallery/user/profile/img_904.jpg';
php > echo basename($path);
img_904.jpg
As a more general example, if you wanted to get the part of a string after the last |
, for example, you could use an approach like this:
php > $string = 'Field 1|Field 2|Field 3';
php > echo substr(strrchr($string, '|'), 1);
Field 3
Or even:
php > $string = 'Field 1|Field 2|Field 3';
php > echo substr($string, strrpos($string, '|') + 1);
Field 3
Edit
You noted problems with UTF-8 handling in basename()
, which is a problem I have run into as well with several versions of PHP. I use the following code as a workaround on UTF-8 paths:
/**
* Returns only the file component of a path. This is needed due to a bug
* in basename()'s handling of UTF-8.
*
* @param string $path Full path to to file.
* @return string Basename of file.
*/
function getBasename($path)
{
$parts = explode('/', $path);
return end($parts);
}
From the PHP basename()
documentation:
Note: basename() is locale aware, so for it to see the correct basename with multibyte character paths, the matching locale must be set using the setlocale() function.
Upvotes: 3
Reputation: 1031
$path = gallery/user/profile/img_904.jpg;
$temp = explode('/', $path);
$filename = $temp[count($temp)-1];
Upvotes: 0
Reputation: 394
<?php
$path = 'gallery/user/profile/img_904.jpg';
$filename = substr(strrchr($path, "/"), 1);
echo $filename;
?>
This will help you ..
Upvotes: 2