diff --git a/modules/filter/filter.module b/modules/filter/filter.module
index 945a90518d2d1be31e71375ccb736778cb89f170..58a3bf4ab9b56215348bd6617bfa842c40e0b295 100644
--- a/modules/filter/filter.module
+++ b/modules/filter/filter.module
@@ -728,7 +728,12 @@ function _filter_html($text, $format) {
   $text = filter_xss($text, $allowed_tags);
 
   if (variable_get("filter_html_nofollow_$format", FALSE)) {
-    $text = preg_replace('/<a([^>]+)>/i', '<a\\1 rel="nofollow">', $text);
+    $html_dom = filter_dom_load($text);
+    $links = $html_dom->getElementsByTagName('a');
+    foreach($links as $link) {
+      $link->setAttribute('rel', 'nofollow');
+    }
+    $text = filter_dom_serialize($html_dom);
   }
 
   return trim($text);
diff --git a/modules/filter/filter.test b/modules/filter/filter.test
index 4f74a1ae3d094639d598b96fa4ebb425fd7c64df..f73be063f78c5559b46b304441dcc33834bf9fb3 100644
--- a/modules/filter/filter.test
+++ b/modules/filter/filter.test
@@ -475,6 +475,10 @@ class FilterUnitTest extends DrupalWebTestCase {
 
     $f = _filter_html('<!--[if true]><a href="http://www.example.com/">text</a><![endif]-->', 'f');
     $this->assertNormalized($f, 'rel="nofollow"', t('Spam deterrent evasion -- link within a comment.'));
+
+    $f = _filter_html('<a href="http://www.example.com/" rel="follow">text</a>', 'f');
+    $this->assertNoNormalized($f, 'rel="follow"', t('Spam deterrent evasion -- with rel set - rel="follow" removed.'));
+    $this->assertNormalized($f, 'rel="nofollow"', t('Spam deterrent evasion -- with rel set - rel="nofollow" added.'));
   }
 
   /**