【问题标题】:PHP replace the very last part of a urlPHP 替换 url 的最后一部分
【发布时间】:2016-04-18 18:40:04
【问题描述】:

我有以下网址 - 虽然此网址并不总是相同,但总是以相同的结尾:

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

这可能吗?

【问题讨论】:

  • 只要使用dirname()
  • 谢谢@Rizier123 - 我不确定如何
  • 那么你得到了除了hqdefault.jpg之外的所有东西,所以你可以将maxresdefault.jpg附加到dirname()的返回值
  • Str_replace?为什么要复杂?您知道开始名称和结束名称。里面没有任何“正则表达式”

标签: php replace preg-replace


【解决方案1】:

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

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

$hq_thumbnail_url = str_replace('hqdefault.jpg', 'maxresdefault.jpg', $thumbnail_url);

希望这会有所帮助!

【讨论】:

    【解决方案2】:

    这是另一种方法,即使hqdefault.jpg 不在网址末尾,它也可以工作:

    $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
    

    【讨论】:

      猜你喜欢
      • 2023-01-04
      • 2019-04-15
      • 1970-01-01
      • 2011-11-15
      • 2013-11-01
      • 2010-12-12
      • 2019-11-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多