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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With