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?
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
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"
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;
Alternative way, check this. Just get first array item.