Build an external link from a field value

When building an external link from a field value you have to do some checking to make sure that "google.com" works as reliably as "http://google.com" as well as variations such as https:// and ftp://. String checks become convoluted to do them correctly and done incorrectly, they can break links that have something other than the planned for scheme of http://.

This method is pretty reliable and includes additional Drupal sanitization and protection through the url() function.

<?php
   $sUrl
= $sValueThatCameFromSomeField;
  
//Parse the url into an array of the parts that make up a URL
  
$aURL = parse_url($sUrl);
  
//Check to see if it has a scheme, provide http:// if it does not.
   
$sUrl = (!empty($aURL['scheme'])) ? $sUrl : 'http://' . $sUrl;
   
//Run it through Drupal's URL function to sanitize it
   
$aOptions = array(
        
'external' => true,
      );
    
$sGoodCleanURL = url($sUrl, $aOptions);
?>

Here is the short code for copying and pasting (same as above without the comments:

<?php
   $sUrl
= $sValueThatCameFromSomeField;
  
$aURL = parse_url($sUrl);
  
$sUrl = (!empty($aURL['scheme'])) ? $sUrl : 'http://' . $sUrl;
  
$sGoodCleanURL = url($sUrl, array( 'external' => true,));
?>

Reference

http://php.net/manual/en/function.parse-url.php
http://api.drupal.org/api/drupal/includes!common.inc/function/url/7

section: