Home » Php » php – Get slug from current url

php – Get slug from current url

Posted by: admin July 12, 2020 Leave a comment

Questions:

I have URLs like so:

http://localhost/hi-every-body/
http://s1.localhost/hello-world/
http://s2.localhost/bye-world/

I want the page “slug” from the URLS, eg.

hi-every-body
hello-world
bye-world

What’s a simple way of doing this in PHP?

How to&Answers:

This should do exactly that:

trim(parse_url($url, PHP_URL_PATH), '/');

It takes the path and strips the forward slashes on both sides.

To get only the last part of the path:

basename(parse_url($url, PHP_URL_PATH));

Answer:

A possibly more robust solution is this:

$slugs = explode("/", $_GET['params']);

This will give you an array filled with every element in your URL.

Eg. http://localhost/one/hippo/cake?t=21

Becomes the array:

Array ( 
   [0] => one 
   [1] => hippo 
   [2] => cake 
)

This allows you to use each element as you require.