PHP替换了url的最后一部分


PHP replace the very last part of a url

我有以下url-尽管这个url并不总是相同的,但结尾总是相同的:

$thumbnail_url = 'http://i2.ytimg.com/vi/552yWya5RgY/hqdefault.jpg'

使用php,我想用maxresdefault.jpg 替换hqdefault.jpg

所以新的缩略图看起来像这样:

$hq_thumbnail_url = 'http://i2.ytimg.com/vi/552yWya5RgY/maxresdefault.jpg'

这可能吗?

str_replace()可能是您最简单的方法。。。

$thumbnail_url = 'http://i2.ytimg.com/vi/552yWya5RgY/hqdefault.jpg';
$hq_thumbnail_url = str_replace('hqdefault.jpg', 'maxresdefault.jpg', $thumbnail_url);

希望这能有所帮助!

这里有另一种方法,即使hqdefault.jpg不在url的末尾,它也能工作:

$url = 'http://i2.ytimg.com/vi/552yWya5RgY/hqdefault.jpg';  // Url you want to change
$newImage = 'newimage.jpg';                                 // New filename 
$splitUrl = explode('/', $url); // Split the url at each '/' occurence
$splitUrl[5] = $newImage;       // Change the old filename (hqdefault.jpg) with the new one
$newUrl = implode('/',$splitUrl);  // Reform the url, but this time, with the new filename.
echo $newUrl;                      // Here's the modified url