【问题标题】:How to insert an additional path into URL using PHP?如何使用 PHP 在 URL 中插入附加路径?
【发布时间】:2012-06-13 05:21:02
【问题描述】:

假设我有这个网址:

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

我想在“image-title”和“987654”之间的部分插入“下载”,所以它看起来像:

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

帮助将不胜感激!谢谢。

【问题讨论】:

  • 您可以使用字符串函数。一种方法是拆分字符串“/”或用您的字符串重构或替换字符串“/image-title/987654”。
  • 假设 987654 是一个变量...只需在它前面加上 "download/" :)

标签: php url urlparse


【解决方案1】:

假设您的 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");

【讨论】:

    【解决方案2】:

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

    • 使用 explode()、array_merge、implode() 进行拆分和重构
    • 使用 substring()
    • 使用正则表达式
    • 使用 str_replace

    假设所有 url 都符合相同的结构 (image-title/[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);
    

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 2021-09-06
        • 1970-01-01
        • 2011-12-06
        • 2010-11-11
        • 1970-01-01
        • 2021-08-03
        • 1970-01-01
        • 2011-07-05
        • 1970-01-01
        相关资源
        最近更新 更多