+

How to add http: // if it is not in the url in PHP?

Syntax:
int preg_match ($pattern, $string, $pattern_array, $flags, $offset) 
Return value:returns true if the template exists, otherwise - false.Example 1:This example takes a URL without http: //and returns the full URL.  
/ / Function to add http function addHttp ( $url ) { // Search by pattern if (! preg_match ( "~ ^ (?: f | ht) tps?: // ~ i " , $url )) { // If doesn`t exist then add http $url = " http: // " . $url ; } // Return URL return $url ; }  
// Declare a variable and initialize
// this is with a URL $url = " engineerforengineer.org " ;  
// Show URL echo $url ; echo "" ;  
// Display URL with http echo addHttp ( $url );  
?>
Exit:
engineerforengineer.org http://engineerforengineer.org 
Example 2: Inthis example takes the URL from http: //and returns without any fixes .   // Function to add http function addHttp (< / code> $url ) { // Search by pattern if (! preg_match ( " ~ ^ (? : f | ht) tps?: // ~ i " , $url )) {   // If doesn`t exist then add http $url = " http: // " . $url ; } // Return URL return $url ; }  
// Declare a variable and initialize
// this is with a URL $url = " http://engineerforengineer.org " ;  
// Show URL echo $url ; echo "" ;  
// Display URL with http echo addHttp ( $url );  
?>
Exit:
http: / /engineerforengineer.org http://engineerforengineer.org 
Method 2:This method uses the parse_url() functionto add http: // if it does not exist in the URL. < tbody>  
// Declare a variable and initialize
// this is with a URL $url = "engineerforengineer.org" ;  
// Show URL echo $url ; echo "" ;  
// Using the parse_url() function // to parse URL $parsed = parse_url ( $url );  
// Check if the parsed URL is empty
// then add http if ( empty ( $parsed [ `scheme` ])) { $url = ` http: // ` . ltrim ( $url , `/` ); }  
// Display the URL echo $url ;  
?>
Exit:
engineerforengineer.org http://engineerforengineer.org 
Method 3:This method uses the strpos()function to add http: // if it doesn`t exist in URL.  
// Declare a variable and
// initialize this $url = "engineerforengineer.org" ;  
// Display the URL echo $url ; echo "" ;  
// Check http: // exists in the URL
// or not, if it doesn`t exist, add it if ( strpos (< / code> $url , ` http: // ` )! == 0) { $url = ` http : // ` . $url ; }  
// Display the URL echo $url ;  
?>
Exit:
engineerforengineer.org http://engineerforengineer.org 
Method 4:This method uses the parse_url() functionto add http: // to the URL if it is not exists.  
// Declare a variable and
// initialize this $url = "engineerforengineer.org" ;  
// Display the URL echo $url ; echo "" ;  
// Function for adding http to URL function addHttp ( $url , $scheme = ` http: // ` ) {  < / code> return parse_url ( $url , PHP_URL_SCHEME) === null? $scheme . $url : $url ; }  
// Display URL echo addHttp ( $url );  
?>
Exit:
engineerforengineer.org http://engineerforengineer.org 
Get Solution for free from DataCamp guru