Adding "http://" to URLs Without Protocols
In instances where a URL does not specify a protocol such as "http://", "https://" or "ftp://", there may be a need to add "http://" to the URL. Here's how to accomplish this:
Function to Add "http://"
The following function can be utilized to add "http://" to URLs without protocols:
function addhttp($url) { if (!preg_match("~^(?:f|ht)tps?://~i", $url)) { $url = "http://" . $url; } return $url; }
Example Usage
Invoking this function with the following URLs will yield the desired results:
addhttp("google.com"); // http://google.com addhttp("www.google.com"); // http://www.google.com addhttp("google.com"); // http://google.com addhttp("ftp://google.com"); // ftp://google.com addhttp("https://google.com"); // https://google.com addhttp("http://google.com"); // http://google.com addhttp("rubbish"); // http://rubbish
Recognizing Various Protocols
This function recognizes the following protocols in a case-insensitive manner:
The above is the detailed content of How Can I Programmatically Add \'http://\' to URLs Missing a Protocol?. For more information, please follow other related articles on the PHP Chinese website!