Retrieve the last part of the URL

need the last part of the url

http://example.com , then the last part is nothing if it is http://example.com/i , then the last part is i if it is http://example.com/i/am/file.php then the last part - file.php

Not sure if I use regex or what

+6
source share
5 answers

This is a simple example:

<?php $url = "http://example.com/i/am/file.php"; $keys = parse_url($url); // parse the url $path = explode("/", $keys['path']); // splitting the path $last = end($path); // get the value of the last element ?> 

Hope this helps you;)

+19
source

There is a function called parse_url () .

+5
source

For those of you who use CMS, such as WordPress or Magento, that add a trailing slash, there is a simple addition to Vasil's solution:

 <?php $url = "http://example.com/i/am/file.php"; $keys = parse_url($url); // parse the url $path = explode("/", $keys['path']); // splitting the path $last = end($path); // get the value of the last element $last = prev($path); // get the next to last element ?> 

You can even just use a simple call URI request like this:

  $request_path = $_SERVER['REQUEST_URI']; $path = explode("/", $request_path); // splitting the path $last = end($path); $last = prev($path); 
+3
source
 $url = 'http://example.com/i/am/file.php'; $url = rtrim($url, '/'); preg_match('/([^\/]*)$/', $url, $match); var_dump($match); 

Test

+2
source

Note that the Vasil example will not work if for some reason you have a trailing slash, for example, some CMS systems will be put at the end (Magento, I look at you ...)

Well, it will work, but the end of the path is empty. Something to know.

0
source

Source: https://habr.com/ru/post/887965/


All Articles