Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get first 3 parts of URL in PHP?

Tags:

url

php

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

For example:

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

The result after getting parts: http://something.com/somebody/somegirls/

This is my code PHP which get 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());

?>
like image 287
user3571494 Avatar asked Apr 25 '14 05:04

user3571494


People also ask

How to extract URL parameters in PHP?

The parameters from a URL string can be retrieved in PHP using parse_url() and parse_str() functions. Note: Page URL and the parameters are separated by the ? character. parse_url() Function: The parse_url() function is used to return the components of a URL by parsing it.

How can I get the last part of a URL in PHP?

Get Last URL Segment If you want to get last URI segment, use array_pop() function in PHP.

How to get URL value in PHP?

The necessary superglobal variables such as $_SERVER['HTTPS'], $_SERVER['REQUEST_URI'], $_SERVER['SERVER_PORT'] are used to get full URL in PHP. The variable HTTPS can easily retrieve the protocol in the URL of a webpage. If it returns a value “on”, then the protocol is HTTPS.

How to get string from URL in PHP?

php $url = 'http://www.example.com/register?name=demo&[email protected]'; $res = parse_url($url); parse_str($res['query'], $params); echo 'Email = '.


2 Answers

Try this,

<?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/
like image 195
Vinod VT Avatar answered Oct 21 '22 13:10

Vinod VT


Assuming that you have grabbed 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

like image 21
Shankar Narayana Damodaran Avatar answered Oct 21 '22 11:10

Shankar Narayana Damodaran