简体   繁体   中英

PHP remove extension from image url

I need to change images extension from jpg / png / gif or else to webp urls from

https://res-3.cloudinary.com/543/image/upload/dpr_auto,w_800,/2342/59_M.jpg

to

https://res-3.cloudinary.com/543/image/upload/dpr_auto,w_800,/2342/59_M.webp

Use preg_replace :

$newUrl = preg_replace('/(?:jpg|png|gif)$/i', 'webp', $url);

Here is the unit test for you:

class UrlReplaceTest extends \PHPUnit_Framework_TestCase
{

    public function testTestUrlReplace()
    {
        $url = 'https://res-3.cloudinary.com/543/image/upload/dpr_auto,w_800,/2342/59_M.jpg';
        $url1 = 'https://res-3.cloudinary.com/543/image/upload/dpr_auto,w_800,/2342/59_M.png';
        $url2 = 'https://res-3.cloudinary.com/543/image/upload/dpr_auto,w_800,/2342/59_M.gif';
        $url3 = 'https://res-3.cloudinary.com/543/image/upload/dpr_auto,w_800,/2342/59_M.webp';
        $url4 = 'https://res-3.cloudinary.com/543/image/upload/dpr_auto,w_800,/2342/59_M.JPG';

        $replacedUrl = $this->replaceImageExtensionInUrlToWebp($url);
        $replacedUrl1 = $this->replaceImageExtensionInUrlToWebp($url1);
        $replacedUrl2 = $this->replaceImageExtensionInUrlToWebp($url2);
        $replacedUrl3 = $this->replaceImageExtensionInUrlToWebp($url3);
        $replacedUrl4 = $this->replaceImageExtensionInUrlToWebp($url4);

        $expected = 'https://res-3.cloudinary.com/543/image/upload/dpr_auto,w_800,/2342/59_M.webp';

        $this->assertEquals($expected, $replacedUrl);
        $this->assertEquals($expected, $replacedUrl1);
        $this->assertEquals($expected, $replacedUrl2);
        $this->assertEquals($expected, $replacedUrl3);
        $this->assertEquals($expected, $replacedUrl4);
    }

    private function replaceImageExtensionInUrlToWebp($url)
    {
        return preg_replace('/(?:jpg|png|gif)$/i', 'webp', $url);
    }
}
$url = "https://res-3.cloudinary.com/543/image/upload/dpr_auto,w_800,/2342/59_M.jpg";
$id = substr($url, strrpos($url, '/') + 1);
$first = dirname($url);
$arr = explode(".", $id);
$last = $arr[0].".webp";
$new_url = $first.'/'.$last;

Simple strings operations:

$s = "https://res-3.cloudinary.com/543/image/upload/dpr_auto,w_800,/2342/59_M.jpg";

$s_result = substr($s, 0, 1 + strrpos($s, ".")) . "webp";

Explained:

// find position of last dot "."
$pos = strrpos( $s, "." );

// loose the extension
// get substring from start of string to the last dot including the dot ( the + 1 )
$s_s = substr($s, 0, 1 + $pos );

// add your string to the end of it
$s_s .= "webp";

This works for any extensions. I think this is the most generic solution for your problem done the way you requested - php, strings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM