How to get the first 3 parts of a URL in PHP?

How to get the first 3 parts of the current URL using PHP.

For instance:

My address: http://something.com/somebody/somegirls/whatever/

Result after receiving parts: http://something.com/somebody/somegirls/

This is my PHP code that gets the current URL:

<?php function curPageURL() { $url = isset( $_SERVER['HTTPS'] ) && 'on' === $_SERVER['HTTPS'] ? 'https' : 'http'; $url .= '://' . $_SERVER['SERVER_NAME']; $url .= in_array( $_SERVER['SERVER_PORT'], array('80', '443') ) ? '' : ':' . $_SERVER['SERVER_PORT']; $url .= $_SERVER['REQUEST_URI']; return $url; } $current_url = str_replace("www.", "", curPageURL()); ?> 
+6
source share
7 answers

Try it,

 <?php $url = 'http://something.com/somebody/somegirls/whatever/'; $parts = explode('/', $url); $new_url = $parts[0].'/'.$parts[1].'/'.$parts[2].'/'.$parts[3].'/'.$parts[4].'/'; echo $new_url; ?> 

OUTPUT

 http://something.com/somebody/somegirls/ 
+8
source

Assuming you grab this URL from your function ...

 <?php $url='http://www.something.com/somebody/somegirls/whatever/'; $parts=explode('/',parse_url($url)['path']); array_unshift($parts,trim(strstr(parse_url($url)['host'],'.'),'.')); print_r(array_filter($parts)); 

OUTPUT :

 Array ( [0] => something.com [2] => somebody [3] => somegirls [4] => whatever ) 

Demonstration

+5
source

You can also use parse_url to get the URL in parts of an array like this:

 $current_url_array = parse_url($current_url); var_dump($current_url_array); 
+2
source

You can use regexp:

 <?php function getFirstUrlContents($Url) { preg_match_all('/^([^\/]*\/){5}/', $Url, $MatchesArray); return $MatchesArray[0]; } var_dump(getFirstUrlContents('http://something.com/somebody/somegirls/whatever/')); ?> 
+1
source
 <?php $url='http://something.com/somebody/somegirls/whatever' ; $explode=explode("/", $url); $search=end($explode); echo $currentUrl=str_replace($search,'',$url); ?> 

Output

 http://something.com/somebody/somegirls/ 
+1
source

Try the following:

 <?php $url = 'http://something.com/somebody/somegirls/whatever/'; $pos = explode('/', $url); for($i=0; $i<5; $i++){ echo $pos[$i].'/'; } ?> 

Exit: http://something.com/somebody/somegirls/

+1
source

Please check the code below.

 function createUrl($array, $pos) { $string = ''; for ($i = 0; $i < $pos; $i++) $string .=$array[$i].'/'; return $string; } $current_url = "http://something.com/somebody/somegirls/xyz/yui"; $initial_string = (stripos($current_url, 'https://') !== FALSE) ? 'https://' : ((strpos($a, 'http://') !== FALSE) ? 'http://' : ''); $last_string = explode('/', substr($a, strlen($initial_string))); $final_url = $initial_string. (count($last_string) > 3) ? createUrl($last_string, 3) : substr($current_url, strlen($initial_string)); echo $final_url; 
+1
source

All Articles