Michael
Michael

Reputation: 6405

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.

Upvotes: 0

Views: 1344

Answers (2)

Gordon
Gordon

Reputation: 316939

Try

  • basename — Returns filename component of path

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.

Upvotes: 3

gurun8
gurun8

Reputation: 3556

Actually pathinfo is little bit better. It gives you basename and more:

http://php.net/manual/en/function.pathinfo.php

<?php
$path_parts = pathinfo('/www/htdocs/index.html');

echo $path_parts['dirname'], "\n";
echo $path_parts['basename'], "\n";
echo $path_parts['extension'], "\n";
echo $path_parts['filename'], "\n"; // since PHP 5.2.0
?>

The above example will output:

/www/htdocs
index.html
html
index

Upvotes: 0

Related Questions