PHP从图片网址中删除扩展程序

时间:2017-10-27 00:48:50

标签: php string

我需要将图片扩展名从end / while / jpg更改为png来自

的网址
gif

webp

3 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

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

答案 2 :(得分:0)

简单的字符串操作:

$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,strings。