3

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.

Will
  • 24,082
  • 14
  • 97
  • 108
Ikhlak S.
  • 8,578
  • 10
  • 57
  • 77

3 Answers3

3

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.

Will
  • 24,082
  • 14
  • 97
  • 108
2
<?php

$path = 'gallery/user/profile/img_904.jpg';
$filename = substr(strrchr($path, "/"), 1);
echo $filename; 


?>

This will help you ..

Kshitij Soni
  • 394
  • 3
  • 17
0
$path = gallery/user/profile/img_904.jpg;
$temp = explode('/', $path);
$filename = $temp[count($temp)-1];
John Pangilinan
  • 953
  • 1
  • 8
  • 25