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 to add http function addHttp( $url ) { // Search the pattern if (!preg_match( "~^(?:f|ht)tps?://~i" , $url )) { // If not exist then add http } // Return the URL return $url ; } // Declare a variable and initialize // it with URL $url = "geeksforgeeks.org" ; // Display URL echo $url ; echo "\n" ; // Display URL with http echo addHttp( $url ); ?> |
neveropen.techHome
Example 2: This example takes the URL with http:// and returns the URL without doing any correction.
<?php // Function to add http function addHttp( $url ) { // Search the pattern if (!preg_match( "~^(?:f|ht)tps?://~i" , $url )) { // If not exist then add http } // Return the URL return $url ; } // Declare a variable and initialize // it with URL // Display URL echo $url ; echo "\n" ; // Display URL with http echo addHttp( $url ); ?> |
Method 2: This method use parse_url() function to add http:// if it does not exist in the url.
<?php // Declare a variable and initialize // it with URL $url = "geeksforgeeks.org" ; // Display URL echo $url ; echo "\n" ; // Use parse_url() function // to parse the URL $parsed = parse_url ( $url ); // Check if parsed URL is empty // then add http if ( empty ( $parsed [ 'scheme' ])) { } // Display the URL echo $url ; ?> |
neveropen.techHome
Method 3: This method use strpos() function to add the http:// if it does not exist in the url.
neveropen.techHome
Method 4: This method use parse_url() function to add http:// in the url if it does not exists.
<?php // Declare a variable and // initialize it $url = "geeksforgeeks.org" ; // Display the url echo $url ; echo "\n" ; // Function to add http in url return parse_url ( $url , PHP_URL_SCHEME) === null ? $scheme . $url : $url ; } // Display URL echo addHttp( $url ); ?> |
neveropen.techHome