phpstringif-statementstr-replace

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!


Solution

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

    $badPhotos = pathinfo($badPhotos, PATHINFO_FILENAME) . '.jpg';
    

    Or like this:

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

    Just for fun, though this may mangle some filenames; remove it if it exists and then add it (DO NOT USE THIS):

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

    For an array:

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