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
Release: 2024-12-02 04:05:10
Original
544 people have browsed it

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;
}
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template