Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the first directory from URL with PHP

Tags:

url

php

parsing

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?

like image 572
user995317 Avatar asked Dec 18 '25 04:12

user995317


2 Answers

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

like image 192
Manoj Yadav Avatar answered Dec 20 '25 16:12

Manoj Yadav


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"
like image 38
nl-x Avatar answered Dec 20 '25 17:12

nl-x



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!