如何以编程方式为图像 URL 添加前缀 PHP?

How to Programmatically Prefix an Image URL with PHP?

我正在使用 PHP 和一个基于 JSON 的 API,returns 2 个字段的值为 属性 照片:

  1. photo_url
  2. has_large

photo_url是普通尺寸的照片URL。

示例: https://secure.example.org/Directory/AnotherDirectory/0008/102/12.jpg

如果 has_large = true,那么我们知道存在大照片,但 API 不 return 具体 URL。

但是,从 API 文档中我们知道,如果我们在图像文件名前加上 'L',这会为我们提供正确的大图像 URL:

示例: https://secure.example.org/Directory/AnotherDirectory/0008/102/L12.jpg

在将文件名写入数据库 (MySQL) 之前,我如何以编程方式在文件名前加上字母 L 前缀 (MySQL)?

注:所有照片的URL结构几乎相同。

图像 URL 中每个 属性 发生变化的唯一部分是:

  1. 第4级目录指定属性 ID (上例中--102)
  2. 文件名本身,最多为 3 个数字(在上面的 URL 示例中 -- 12.jpg).

经过数小时对 RegEx、preg_replace() 的研究并在 Whosebug 上寻找类似的解决方案后,我仍然不确定如何使用 PHP.

正确完成此操作

如有任何帮助,我们将不胜感激。提前致谢。

看来您只需要在文件名(不带路径)前加上L。没有路径的文件名除了字符串末尾的 / 外,在正则表达式中看起来是 ([^\/]+)$。因此所需的替换函数是:

$large_photo_url = preg_replace('/([^\/]+)$/', 'L', $photo_url);

这里我们使用 explode 函数,split / 上的字符串,然后将 L 附加到该数组的最后一个值。

解决方案一:

Try this code snippet here

<?php

$link="https://secure.example.org/Directory/AnotherDirectory/0008/102/12.jpg";
$portions=explode("/",$link);
$portions[count($portions)-1]="L".$portions[count($portions)-1];
print_r(implode("/", $portions));

方案二:

正则表达式: ([^\/]+)$

1. ([^\/]+) match all till /(not including this), here circle () braces will capture the first captured result in </code>,</p> <p><strong>2.</strong> <code>$ end of string.

Regex demo

<?php

$link="https://secure.example.org/Directory/AnotherDirectory/0008/102/12.jpg";
echo preg_replace("/([^\/]+)$/", 'L', $link);

对于我的情况.. 我正在使用这个函数来获取更新后的图像 url.

function thumb_url($image_url=''){

    $prefix = 'thumb';
    $photo_url = preg_replace('/([^\/]+)$/', "{$prefix}", $image_url); 

    return $photo_url;
}

归功于@Dmitry。我刚刚在这里使用了他的代码。