phpparsingurl

Get the first directory from URL with PHP


I have url in variable like this:

$url = 'http://mydomain.com/yep/2014-04-01/some-title';

Then what I want is to to parse the 'yep' part from it. I try it like this:

$url_folder = strpos(substr($url,1), "/"));

But it returns some number for some reason. What I do wrong?


Solution

  • Use explode, Try this:

    $url = 'http://example.com/yep/2014-04-01/some-title';
    $urlParts = explode('/', str_ireplace(array('http://', 'https://'), '', $url));
    echo $urlParts[1];
    

    Demo Link