Forum Moderators: coopster

Message Too Old, No Replies

Remove .jpg from string.jpg

         

PeteM

8:38 pm on Sep 22, 2006 (gmt 0)

10+ Year Member



What's the easiest way of removing the characters '.jpg' from the end of a file name?

Cheers, Pete

eelixduppy

8:55 pm on Sep 22, 2006 (gmt 0)



Something like this:

$string = "image.jpg";
$new_string = [url=http://us2.php.net/manual/en/function.str-replace.php]str_replace[/url](".jpg","",$string);
echo $new_string;

Good luck!

RonPK

8:56 pm on Sep 22, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



$filename = preg_replace("/\.jpg$/i", "", $filename);

RonPK

9:21 pm on Sep 22, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



A brief comparison of str_replace and preg_replace:

* with str_replace the position of the substring within the string cannot be taken into account. So if the filename is something odd like "foo.jpgbar.doc", using str_replace as in eelixduppy's example would result in "foobar.doc".

* preg_replace as used in the other example does not have that disadvantage. But it does use a regular expression, and matching such patterns requires more server resources. Hardly noticeable, but present.

Conclusion: if you're sure that there will not be weird filenames as "foo.jpgbar.doc", use str_replace. Otherwise, use preg_replace.

eelixduppy

9:28 pm on Sep 22, 2006 (gmt 0)



Nice, RonPK. I wasn't thinking along those lines. Glad you got my back ;)

PeteM

9:33 pm on Sep 22, 2006 (gmt 0)

10+ Year Member



Cheers guys, it's been a long week!

eelixduppy

10:46 pm on Sep 22, 2006 (gmt 0)



I discovered this based on the topic of another thread:

$string = "image.jpg";
$new_string = [url=http://us2.php.net/manual/en/function.basename.php]basename[/url]($string,".jpg");
echo $new_string;

I'm not sure if the suffix parameter is case-sensitive or not.

I guess you really do learn something new every day. In my case, more than just something, but many things. ;)

RonPK

11:21 pm on Sep 22, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



> basename(string [,suffix])

LOL, I didn't know that one. That's PHP: there is a native method for almost every purpose one can think of ;)

TerranRich

2:05 am on Sep 23, 2006 (gmt 0)

10+ Year Member



That's why PHP is so lovely. :)

I must discover a new inbuilt function everyday.

Psychopsia

3:04 am on Sep 23, 2006 (gmt 0)

10+ Year Member



eelixduppy:

basename suffix is case-sensitive.

basename($string, ".jpg"); and basename($string, ".JPG"); are not the same. :)

[edited by: Psychopsia at 3:05 am (utc) on Sep. 23, 2006]