Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add .jpg to end of string if it doesn't exist

I have the "original list" and I'm trying to convert it to the "desired list" using php. When the .jpg is present at the end of the string, I want to do nothing. If .jpg isn't the end of the string, I want to add .jpg to the end. The "original list" of stored in $badPhotos as one long string.

   Original List                                      Desired List
http://i.imgur.com/4ReyOhl                    http://i.imgur.com/4ReyOh1.jpg
http://i.imgur.com/4ReyOh2.jpg                http://i.imgur.com/4ReyOh2.jpg
http://i.imgur.com/4ReyOh3                    http://i.imgur.com/4ReyOh3.jpg
http://i.imgur.com/4ReyOh4                    http://i.imgur.com/4ReyOh4.jpg
http://i.imgur.com/4ReyOh5.jpg                http://i.imgur.com/4ReyOh5.jpg

I've been using the following to modify a strings if someone added a , where a . belongs, but now I need to modify the sting only if the string doesn't end in .jpg.

$badPhotos = str_replace(',', '.', $badPhotos);

Ideas? Thanks!

like image 680
Mr. B Avatar asked Nov 30 '22 09:11

Mr. B


1 Answers

Just for fun, remove it if it exists and then add it:

$badPhotos = rtrim($badPhotos, '.jpg') . '.jpg';

For an array:

$badPhotos = array_map(function($v) {
                           return rtrim($v, '.jpg') . '.jpg';
                       },
                       $badPhotos);

Or more appropriate for file names, just get the name without the extension and then add it:

$badPhotos = pathinfo($badPhotos, PATHINFO_FILENAME) . '.jpg';
like image 71
AbraCadaver Avatar answered Dec 01 '22 21:12

AbraCadaver