views:

196

answers:

2

Hello ,

I have a php application that saves the pictures on the server and also stores the picture names in the database . The issue that I have is that the picture names include the path/folder where it was saved from (e.g 1220368812/chpk2198933_large-2.jpg) so I need a str_replace pattern to remove "1220368812/" and have the picture name correct stored in the db . Also I would appreciate if you will send me a good link that explains how exactly the str_replace patterns work or at least how the pattern that you use work .

+3  A: 

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.

Gordon
umm downvote? for what?
Gordon
Surely you're accustom to the *"drive-by-down-voters"* by now? :)
Bart Kiers
A: 

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
gurun8
If user331071 needs to get more info than the basename (something not mentioned in the OP), then `pathinfo` might be better (what is "better" in this context anyway?). But, to only retrieve the basename of a file, I'd go for Gordon's suggestion: only one line of code from which it's very clear what it does. Your suggestion takes an extra line of code and uses an array lookup (far less expressive, IMO).
Bart Kiers
... it doesn't hurt to know `pathinfo` exists, of course! :)
Bart Kiers
With basename() you only get the basename and no extension data. Based upon the OP requires, by using the basename() function to extract the filename, you'd have have a workaround for the extension. pathinfo() will give you that as well. It's 1 stop shopping. basename() is not.
gurun8
@Bart K. it is of course possible for a `pathinfo` one-liner too: `pathinfo($path, PATHINFO_BASENAME)`
salathe
@salathe, didn't know that, thanks for the info (I know little PHP...). But still, choosing between `basename($path)` and `pathinfo($path, PATHINFO_BASENAME)`, I'd go for the first anyway.
Bart Kiers