如何使用 PHP 在 URL 中插入其他路径


How to insert an additional path into URL using PHP?

假设我有这个网址:

http://example.com/image-title/987654/

我想在"

图像标题"和"987654"之间的部分插入"下载",使其看起来像:

http://example.com/image-title/download/987654/

帮助将不胜感激!谢谢。

假设您的 URI 始终是相同(或至少可预测)的格式,您可以使用 explode 函数将 URI 拆分为其每个部分,然后使用 array_splice 将元素插入该数组,最后使用 implode 将它们全部重新组合成一个字符串。

请注意,您可以通过将 $length 参数指定为零来将元素插入数组中。例如:

$myArray = array("the", "quick", "fox");
array_splice($myArray, 2, 0, "brown");
// $myArray now equals array("the", "quick", "brown", "fox");

在 PHP 中有很多方法可以做到这一点:

  • 使用 explode()、array_merge、内爆 () 进行拆分和重建
  • 使用子字符串()
  • 使用正则表达式
  • 使用str_replace

假设所有网址都符合相同的结构(图像标题/[image_id]),我建议使用这样的str_replace:

$url = str_replace('image-title', 'image-title/download', $url);
但是,如果图像标题

是动态的(图像的实际标题),我建议像这样拆分和重建:

$urlParts = explode('/', $url);
$urlParts = array_merge(array_slice($urlParts, 0, 3), (array)'download', array_slice($urlParts, 3));
$url = implode('/', $urlParts);

格式不是很好,但我认为这就是你需要的

$mystr= 'download';
$str = 'http://example.com/image-title/987654/';
$newstr = explode( "http://example.com/image-title",$str);
$constring =  $mystr.$newstr[1];

$adding = 'http://example.com/image-title/';
echo $adding.$constring;  // output-- http://example.com/image-title/download/987654/