Remove http, path or domain name from url using PHP

In this article, I am going to show you how to remove or separate http, www, path, query, and fragments from a URL input using PHP code. This post is going to help you while creating tool website projects.

I am using a predefined function to do this: parse_url(). This function helps us to divide the URL in form of an array.

The array looks like this:

    [scheme] => http
    [host] => hostname
    [user] => username
    [pass] => password
    [path] => /path
    [query] => arg=value
    [fragment] => anchor

Remove http:// from URL

http means hypertext transfer protocol. If you are taking input using the type=url attribute then the user can only submit URLs with HTTP. That's why the URL looks like this: Sometimes you would need to remove http from the URL. 

Try this code to do this kind of stuff:

$url = "";
$url = preg_replace("#^[^:/.]*[:/]+#i", "", $url);
echo $url;


Display the URL without path and other stuff

without http

$url = "";
echo $url['host'];


with http

$url = "";
$schem = $url['scheme'];
$host = $url['host'];
echo "$schem://$host"


Display query separately from URL

A query in URL is known as the search query that appears in the address bar or browser bar. The query string is the part of a URL that follows the question mark (?) and precedes the hash symbol ( # ). It is used to send information to a server program.


$url = "";
echo $url['query'];

Output: m=1

Display fragments separately from the URL

fragments – also known as URL hash, content hash or anchor in URL. It is used by browsers to identify specific sections of a web page. fragments in URL are used to provide additional clickable options such as search results, related content and so on.


$url = "";
echo $url['fragment'];

Output: #myself


Post a Comment