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.

loading
The array looks like this:

Array
(
    [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: http://fluratech.com. Sometimes you would need to remove http from the URL. 

Try this code to do this kind of stuff:

$url = "https://www.fluratech.com/2022/08/10-awesome-php-projects-for-beginners.html?m=1#myself";
$url = preg_replace("#^[^:/.]*[:/]+#i", "", $url);
echo $url;

Output: www.fluratech.com/2022/08/10-awesome-php-projects-for-beginners.html?m=1#myself

Display the URL without path and other stuff

without http

$url = "https://www.fluratech.com/2022/08/10-awesome-php-projects-for-beginners.html?m=1#myself";
$url=(parse_url($url));
echo $url['host'];

Output: www.fluratech.com

with http

$url = "https://www.fluratech.com/2022/08/10-awesome-php-projects-for-beginners.html?m=1#myself";
$url=(parse_url($url));
$schem = $url['scheme'];
$host = $url['host'];
echo "$schem://$host"

Output: https://www.fluratech.com

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.

EXAMPLE: https://fluratech.com?m=1

$url = "https://www.fluratech.com/2022/08/10-awesome-php-projects-for-beginners.html?m=1#myself";
$url=(parse_url($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.

EXAMPLE: https://fluratech.com#popular-posts

$url = "https://www.fluratech.com/2022/08/10-awesome-php-projects-for-beginners.html?m=1#myself";
$url=(parse_url($url));
echo $url['fragment'];

Output: #myself

Discussions

Post a Comment