Strip http:// and https:// from URL

Dealing with those pesky url prefixes on a user based input case.

For example, you have a custom field in your WordPress post that is intended to hold URL. If it’s your own blog, you, as a web savvy person, know to put the http:// or https:// in front of the URL. But if the blog has many authors, or you just want to make your UI for humans, you could give it a little attention.

Check the commented code below.

  //If it's not empty
  if (!empty($link)) {
    //If it begins with https...
    if (preg_match('/^https/', $link)) {
      //...then we'll set the $url_prefix variable to https://
      $url_prefix = 'https://';
    } else {
      //If it does not begin with https we'll use http
      $url_prefix = 'http://';
    //Get rid of the http:// or https://
    $link = str_replace(array('http://','https://'), '', $link);

I don’t know if this is the smartest way, let me know in the comments if you got something better.


  • Ion Saliu says:

    I have AdSense on my site. I recently moved from http to https. All of a sudden, the ads were not showing on my Web pages!

    Google advised to remove http from their scripts. I did a global replace. Instead of http://, the scripts only showed //. For example: src=”//pagead2…

    This matter is very complicated and nobody knows for sure how it works across the Internet. I have many pages with the canonical meta tag; e.g.
    That creates problems because I have many pages with that meta tag. It is not sure how it would work in different browsers if I strip http. I can try here:
    The URL doesn’t work in edit mode…

Club-Mate, the beverage →