【问题标题】:How do i get the part of the url in php [duplicate]我如何在php中获取url的一部分[重复]
【发布时间】:2018-09-18 05:46:36
【问题描述】:

如何获取网址的最后 3 部分

例如,我有如下链接

http://www.yoursite/one/two/three/drink.pdf

我将使用以下代码获取网址的最后一部分

$url = "http://www.yoursite/one/two/three/drink.pdf";
echo $end = end((explode('/', $url)));

但我需要 URL 中的最后 3 部分,如下所示

/two/three/drink.pdf

请给我一个解决方案。

【问题讨论】:

  • 奇怪的问题...如果您仍然使用explode() 将路径组件分开,那么您为什么不能简单地使用返回的最后三个元素?
  • 如果http://www.yoursite/one 在您的网址中保持不变,那么您可以使用echo ('http://www.yoursite/one/two/three/drink.pdf',23);,其中23 是您要省略的http://www.yoursite/one 的长度。

标签: php


【解决方案1】:

你可以这样做:

<?php

    $url = "http://www.yoursite/one/two/three/drink.pdf";
    $ex = explode('/', $url);

    $arr = array_slice($ex, -3, 3);
    $output = '/'.implode('/', $arr);
    var_dump($output);    // Outputs /two/three/drink.pdf

首先,您使用explodeurl 字符串分解为array。然后使用array_slice 获取数组的最后三个元素,最后使用implode 使用/ 作为粘合剂将数组元素粘合回来。

将所有内容放在一行中如下所示:

echo '/'.implode('/', array_slice(explode('/', $url), -3, 3));

【讨论】:

    【解决方案2】:

    试试下面的代码

    $url = "http://www.yoursite/one/two/three/drink.pdf";
    $url_array = (explode('/', $url));
    print_r(array_slice($url_array,-3,3));
    

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-04
      • 2011-10-22
      • 2021-11-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多