phpfilenamestext-extractiontext-parsing

Get only the filename from a filepath string


I have filepath strings and I need to remove their filepath.

e.g. 1220368812/chpk2198933_large-2.jpg)

I need a str_replace() pattern to remove 1220368812/ leaving only the filename.


Solution

  • Try

    Example #1 basename() example

    $path = "/home/httpd/html/index.php";
    $file = basename($path);         // $file is set to "index.php"
    $file = basename($path, ".php"); // $file is set to "index"
    

    There is no need to str_replace anything, because basename will remove the path part. Also, str_replace does not allow for patterns. All it does is replace all occurrences of the search string with the replacement string. Replacement by patterns is done with Regular Expressions, but they are not necessary here either.