There are many approaches to add http:// in the URL if it doesn’t exist. Some of them are discussed below.
Method 1: Using preg_match() function: This function searches string for pattern and returns true if pattern exists, otherwise returns false. Usually, the search starts from the beginning of the subject string. The optional parameter offset is used to specify the position from where to start the search.
Syntax:
int preg_match($pattern, $string, $pattern_array, $flags, $offset )
Return value: It returns true if pattern exists, otherwise false.
Example 1: This example takes the URL without http:// and returns the complete URL.
<?php
function addHttp( $url ) {
if (!preg_match( "~^(?:f|ht)tps?://~i" , $url )) {
}
return $url ;
}
$url = "geeksforgeeks.org" ;
echo $url ;
echo "\n" ;
echo addHttp( $url );
?>
|
Output:
geeksforgeeks.org
http://geeksforgeeks.org
Example 2: This example takes the URL with http:// and returns the URL without doing any correction.
<?php
function addHttp( $url ) {
if (!preg_match( "~^(?:f|ht)tps?://~i" , $url )) {
}
return $url ;
}
echo $url ;
echo "\n" ;
echo addHttp( $url );
?>
|
Output:
http://geeksforgeeks.org
http://geeksforgeeks.org
Method 2: This method use parse_url() function to add http:// if it does not exist in the url.
<?php
$url = "geeksforgeeks.org" ;
echo $url ;
echo "\n" ;
$parsed = parse_url ( $url );
if ( empty ( $parsed [ 'scheme' ])) {
$url = 'http://' . ltrim( $url , '/' );
}
echo $url ;
?>
|
Output:
geeksforgeeks.org
http://geeksforgeeks.org
Method 3: This method use strpos() function to add the http:// if it does not exist in the url.
<?php
$url = "geeksforgeeks.org" ;
echo $url ;
echo "\n" ;
if ( strpos ( $url , 'http://' ) !== 0) {
}
echo $url ;
?>
|
Output:
geeksforgeeks.org
http://geeksforgeeks.org
Method 4: This method use parse_url() function to add http:// in the url if it does not exists.
<?php
$url = "geeksforgeeks.org" ;
echo $url ;
echo "\n" ;
function addHttp( $url , $scheme = 'http://' ) {
return parse_url ( $url , PHP_URL_SCHEME) === null ?
$scheme . $url : $url ;
}
echo addHttp( $url );
?>
|
Output:
geeksforgeeks.org
http://geeksforgeeks.org
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
27 Feb, 2019
Like Article
Save Article