Can't get the last part of url

Sevengames Xoom

I'm trying to get the last part of this url string: national/italy/serie-a/20152016/s11663/

my goal is get: s11663 this is my code:

$path = parse_url("national/italy/serie-a/20152016/s11663/", PHP_URL_PATH);
$pathFragments = explode('/', $path);
$end = end($pathFragments);
var_dump($end);

but I get:

string(0) ""

what I did wrong?

FirstOne

Because you have a trailing / in the end, you have to get the second last:

$path = parse_url("national/italy/serie-a/20152016/s11663/", PHP_URL_PATH);
$pathFragments = explode('/', $path);
array_pop($pathFragments); // remove last (empty value)
$end = end($pathFragments);
var_dump($end);

Take a look at the output of $pathFragments on your question:

Array
(
    [0] => national
    [1] => italy
    [2] => serie-a
    [3] => 20152016
    [4] => s11663
    [5] => 
)

This code will work for strings ending with and without /:

$path = parse_url("national/italy/serie-a/20152016/s11663", PHP_URL_PATH);
$pathFragmenst = (substr($path, -1) == '/') ? 
    $pathFragments = explode('/', $path, -1) :
    $pathFragments = explode('/', $path);

$end = end($pathFragments);
var_dump($end);

Output for ../s11663/: https://3v4l.org/BWjkd

string(6) "s11663"

Output for ../s11663: https://3v4l.org/H7fP9

string(6) "s11663"


Notes:

1 - This code:

$pathFragmenst = (substr($path, -1) == '/') ? 
    $pathFragments = explode('/', $path, -1) :
    $pathFragments = explode('/', $path);

Is short for this:

if(substr($path, -1) == '/'){
    $pathFragments = explode('/', $path, -1);
}else{
    $pathFragments = explode('/', $path);
}

2 - I don't know if that string is the result of the url_parse, or you are really trying to parse it, but

var_dump(parse_url("national/italy/serie-a/20152016/s11663", PHP_URL_PATH));

will output

string(38) "national/italy/serie-a/20152016/s11663"

, so there is not need to parse_url it - unless you are trying to parse something like:

http://example.com/national/italy/serie-a/20152016/s11663/
^^^^^^^^^^^^^^^^^^^

I left it as is in case you are going to use the complete url...

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related