PHP从图片URL中删除扩展名

cnjp1d6j  于 2023-11-16  发布在  PHP
关注(0)|答案(4)|浏览(196)

我需要改变图片扩展从jpg/png/gif或其他webp网址从

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

字符串

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

2w2cym1i

2w2cym1i1#

使用preg_replace

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

字符串
下面是为您准备的单元测试:

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);
    }
}

kuhbmx9i

kuhbmx9i2#

$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;

字符串

koaltpgm

koaltpgm3#

简单的字符串操作:

$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";

字符串
解释:

// 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";


这适用于任何扩展。我认为这是最通用的解决方案,为您的问题做的方式,你要求- php,字符串。

1cklez4t

1cklez4t4#

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

字符串
在回答中有错误的信息遗漏这里才是正确的方法。

相关问题