diff --git a/core/lib/Drupal/Component/Utility/Xss.php b/core/lib/Drupal/Component/Utility/Xss.php
index 6d461d3f02..ca146b1833 100644
--- a/core/lib/Drupal/Component/Utility/Xss.php
+++ b/core/lib/Drupal/Component/Utility/Xss.php
@@ -265,6 +265,10 @@ protected static function attributes($attributes) {
           break;
 
         case 2:
+          // Once we've finished processing the attribute value continue to look
+          // for attributes.
+          $mode = 0;
+          $working = 1;
           // Attribute value, a URL after href= for instance.
           if (preg_match('/^"([^"]*)"(\s+|$)/', $attributes, $match)) {
             $value = $skip_protocol_filtering ? $match[1] : UrlHelper::filterBadProtocol($match[1]);
@@ -272,8 +276,6 @@ protected static function attributes($attributes) {
             if (!$skip) {
               $attributes_array[] = "$attribute_name=\"$value\"";
             }
-            $working = 1;
-            $mode = 0;
             $attributes = preg_replace('/^"[^"]*"(\s+|$)/', '', $attributes);
             break;
           }
@@ -284,8 +286,6 @@ protected static function attributes($attributes) {
             if (!$skip) {
               $attributes_array[] = "$attribute_name='$value'";
             }
-            $working = 1;
-            $mode = 0;
             $attributes = preg_replace("/^'[^']*'(\s+|$)/", '', $attributes);
             break;
           }
@@ -296,15 +296,13 @@ protected static function attributes($attributes) {
             if (!$skip) {
               $attributes_array[] = "$attribute_name=\"$value\"";
             }
-            $working = 1;
-            $mode = 0;
             $attributes = preg_replace("%^[^\s\"']+(\s+|$)%", '', $attributes);
           }
           break;
       }
 
       if ($working == 0) {
-        // Not well formed; remove and try again.
+        // Not well-formed; remove and try again.
         $attributes = preg_replace('/
           ^
           (
diff --git a/core/tests/Drupal/Tests/Component/Utility/XssTest.php b/core/tests/Drupal/Tests/Component/Utility/XssTest.php
index db5ee1d7b9..5cc176f7bd 100644
--- a/core/tests/Drupal/Tests/Component/Utility/XssTest.php
+++ b/core/tests/Drupal/Tests/Component/Utility/XssTest.php
@@ -533,6 +533,24 @@ public function providerTestAttributes() {
         'Link tag with numeric data attribute',
         ['a'],
       ],
+      [
+        '<img src= onmouseover="script(\'alert\');">',
+        '<img>',
+        'Image tag with malformed SRC',
+        ['img'],
+      ],
+      [
+        'Body"></iframe><img/src="x"/onerror="alert(document.domain)"/><"',
+        'Body"&gt;<img />&lt;"',
+        'Image tag with malformed SRC',
+        ['img'],
+      ],
+      [
+        '<img/src="x"/onerror="alert(document.domain)"/>',
+        '<img />',
+        'Image tag with malformed SRC',
+        ['img'],
+      ],
     ];
   }
 
