diff --git a/link.module b/link.module
index c7af1ff..64f2140 100644
--- a/link.module
+++ b/link.module
@@ -421,6 +421,9 @@ function _link_sanitize(&$item, $delta, &$field, $instance, &$node) {
     $type = LINK_EXTERNAL;
   }
   $url = link_cleanup_url($item['url']);
+  // The $item['url'] assignment needs to happen before any substr() calls.
+  // Otherwise the url token will receive an incomplete URL as input.
+  $item['url'] = check_plain($url);
 
   // Separate out the anchor if any.
   if (strpos($url, '#') !== FALSE) {
@@ -435,8 +438,6 @@ function _link_sanitize(&$item, $delta, &$field, $instance, &$node) {
     $url = substr($url, 0, strpos($url, '?'));
   }
 
-  $item['url'] = check_plain($url);
-
   // Create a shortened URL for display.
   $display_url = $type == LINK_EMAIL ?
                   str_replace('mailto:', '', $url) :
