Search code examples
phpurldecode

Output a part of URL in php


So, I have dynamically generated pages that follows the following format:

 http://example.com/name/first_name/last_name/John%2C+Smith

What is the php code to output the last part of the url?

so, it becomes like "John, Smith".

Thank you so much.

EDIT:

I realized that the URL is ended with another / and the answers given below does not pick it up. What change should I make?

http://example.com/name/first_name/last_name/John%2C+Smith/

EDIT 2:

So, the link is dynamically generated as the following:

href="http://example.com/name/first_name/last_name/<?php echo $full_name ?>"

Solution

  • You can use parse_url with second parameter PHP_URL_PATH

    $url = urldecode("http://example.com/name/first_name/last_name/John%2C+Smith");
    $arr = array_filter(explode('/',parse_url($url, PHP_URL_PATH)));
    print_r(end($arr));
    

    Edited:

    As per requirement for dynamic url you can use

    $url = urldecode("http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]");