clubmate.fi

A good[ish] website

Web development blog, loads of UI and JavaScript topics

Strip the protocol from an URL using PHP

Filed under: php— Tagged with: regex

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

For example, if you have a custom field in your WordPress post that is intended to hold URL, and it's your own blog, it’s probably not a problem, you 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 more humane, you could give it a little attention.

Check the commented code below:

<?php
  // Get the custom field value (we're using the wpalchemy class)
  $link = $custom_metabox->get_the_value('link');

  if (!empty($link)) {
    // Begins with https
    if (preg_match('/^https/', $link)) {
      // Set the $url_prefix variable to `https://`
      $url_prefix = 'https://';
    } else {
      // Use http
      $url_prefix = 'http://';
    }

    // Get rid of the `http://` or `https://`
    $link = str_replace(array('http://', 'https://'), '', $link);
  ?>
  <a href="<?php echo $url_prefix . $link; ?>">
    <?php echo $link; ?>
  </a>
  <?php
}
?>

Comments would go here, but the commenting system isn’t ready yet, sorry. Tweet me @hiljaa if you want to make a correction etc.

  • © 2021 Antti Hiljá
  • About
  • Follow me in Twatter → @hiljaa
  • All rights reserved yadda yadda.
  • I can put just about anything here, no one reads the footer anyways.
  • I love u!