Home >Backend Development >PHP Tutorial >How Can I Programmatically Add \'http://\' to URLs Missing a Protocol?

How Can I Programmatically Add \'http://\' to URLs Missing a Protocol?

Linda Hamilton
Linda HamiltonOriginal
2024-12-02 04:05:10620browse

How Can I Programmatically Add

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:

  • http://
  • https://
  • ftp://
  • ftps://

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn