我如何在php中获得网址的一部分

时间:2018-09-18 05:46:36

标签: php

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

例如,我有如下链接

<button type="button" class="btn btn-primary" (click)="openModal(template)">Open first modal</button>

<ng-template #template>
  <div class="modal-header">
    <h4 class="modal-title pull-left">First modal</h4>
    <button type="button" class="close pull-right" aria-label="Close" (click)="modalRef.hide()">
      <span aria-hidden="true">&times;</span>
    </button>
  </div>
  <div class="modal-body">
    This is a first modal
    <button type="button" class="btn btn-primary" (click)="openModal2(templateNested)">Open second modal</button>
  </div>
</ng-template>

<ng-template #templateNested>
  <div class="modal-header">
    <h4 class="modal-title pull-left">Second modal</h4>
    <button type="button" class="close pull-right" aria-label="Close" (click)="modalRef2.hide()">
      <span aria-hidden="true">&times;</span>
    </button>
  </div>
  <div class="modal-body">
    This is nested modal.<br>
    <button *ngIf="modalRef" type="button" class="btn btn-danger" (click)="closeFirstModal()">Close first modal</button>
  </div>
</ng-template>

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

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

但是我需要URL的最后三部分,如下所示

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

请为我提供解决方案。

2 个答案:

答案 0 :(得分: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));

答案 1 :(得分:0)

尝试下面的代码

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

希望这会有所帮助。