Question

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?

Was it helpful?

Solution

Use explode, Try this:

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

Demo Link

OTHER TIPS

Well, first of all the substr(...,1) will return to you everthing after position 1. So that's not what you want to do.

So http://mydomain.com/yep/2014-04-01/some-title becomes ttp://mydomain.com/yep/2014-04-01/some-title

Then you are doing strpos on everthing after position 1 , looking for the first / ... (Which will be the first / in ttp://mydomain.com/yep/2014-04-01/some-title). The function strpos() will return you the position (number) of it. So it is returning you the number 4.

Rather you use explode():

$parts = explode('/', $url);
echo $parts[3]; // yep
// $parts[0] = "http:"
// $parts[1] = ""
// $parts[2] = "mydomain.com"
// $parts[3] = "yep"
// $parts[4] = "2014-04-01"
// $parts[4] = "some-title"

The most efficient solution is the strtok function:

strtok($path, '/')

So complete code would be :

$dir = strtok(parse_url($url, PHP_URL_PATH), '/')

Use parse_url function.

$url = 'http://mydomain.com/yep/2014-04-01/some-title';
$url_array = parse_url($url);
preg_match('@/(?<path>[^/]+)@', $url_array['path'], $m);
$url_folder = $m['path'];
echo $url_folder;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top