Index: filter.module
===================================================================
--- filter.module	(revision 39856)
+++ filter.module	(working copy)
@@ -720,9 +720,20 @@
   }
 
   if (variable_get("filter_html_nofollow_$format", FALSE)) {
-    $text = preg_replace('/<a([^>]+)>/i', '<a\\1 rel="nofollow">', $text);
+    // Ignore warnings during HTML soup loading.
+    $htmlDom = @DOMDocument::loadHTML('<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /></head><body>' . $text . '</body></html>');
+    $bodyNode = $htmlDom->getElementsByTagName('body')->item(0);
+    $links = $bodyNode->getElementsByTagName('a');
+    foreach($links as $link) {
+      $link->setAttribute('rel', 'nofollow');
+    }
+    if (preg_match("|^<body[^>]*>(.*)</body>$|s", $htmlDom->saveXML($bodyNode), $matches)) {
+      $body_content = $matches[1];
+      // The XHTML guidelines recommend to include a space before the trailing /
+      // and > of empty elements for better rendering on HTML user agents.
+      $text = preg_replace('|<([^>]*)/>|i', '<$1 />', $body_content);
+    }
   }
-
   return trim($text);
 }
 
@@ -1253,4 +1264,4 @@
 
 /**
  * @} End of "Standard filters".
- */
+ */
\ No newline at end of file
