iSaumya
iSaumya

Reputation: 1623

How to get first part of a URL

can anyone help me to piece together the puzzled I'm facing. Lets say I have url's

/some-work/

/store/bread/alloy/

and in both of these cases I wanna fetch the first part from it. i.e. some-work, store.

Now I've used parse_url(get_permalink()) to get the array of the url and then fetch the path index of the array to fetch the above string. Now I have also checked strstr PHP function, but I am unable to make it work. Can anyone help?

Upvotes: 1

Views: 3754

Answers (1)

Narendrasingh Sisodia
Narendrasingh Sisodia

Reputation: 21437

You can use explode, array_filter and current function like as

$url = "http://www.example.com/some-work/";
$extracted = array_filter(explode("/",parse_url($url,PHP_URL_PATH)));
echo current($extracted);//some-work

Demo

Upvotes: 9

Related Questions