diff --git a/core/lib/Drupal/Core/Url.php b/core/lib/Drupal/Core/Url.php
index b2e3062..7e30935 100644
--- a/core/lib/Drupal/Core/Url.php
+++ b/core/lib/Drupal/Core/Url.php
@@ -253,10 +253,10 @@ public static function fromUri($uri, $options = []) {
     // Extract query parameters and fragment and merge them into $uri_options,
     // but preserve the original $options for the fallback case.
     $uri_options = $options;
-    if (!empty($uri_parts['fragment'])) {
+    if (isset($uri_parts['fragment'])) {
       $uri_options += ['fragment' => $uri_parts['fragment']];
+      unset($uri_parts['fragment']);
     }
-    unset($uri_parts['fragment']);
     if (!empty($uri_parts['query'])) {
       $uri_query = [];
       parse_str($uri_parts['query'], $uri_query);
@@ -431,7 +431,7 @@ public function toUriString() {
       $uri = $this->uri;
     }
     $query = !empty($this->options['query']) ? ('?' . UrlHelper::buildQuery($this->options['query'])) : '';
-    $fragment = !empty($this->options['fragment']) ? '#' . $this->options['fragment'] : '';
+    $fragment = isset($this->options['fragment']) ? '#' . $this->options['fragment'] : '';
     return $uri . $query . $fragment;
   }
 
diff --git a/core/tests/Drupal/Tests/Core/UrlTest.php b/core/tests/Drupal/Tests/Core/UrlTest.php
index b26feb8..1884608 100644
--- a/core/tests/Drupal/Tests/Core/UrlTest.php
+++ b/core/tests/Drupal/Tests/Core/UrlTest.php
@@ -492,6 +492,14 @@ public function providerTestEntityUris() {
         NULL,
       ],
       [
+        'entity:test_entity/1#0',
+        [],
+        'entity.test_entity.canonical',
+        ['test_entity' => '1'],
+        NULL,
+        '0',
+      ],
+      [
         'entity:test_entity/2?page=1&foo=bar#bottom',
         [], 'entity.test_entity.canonical',
         ['test_entity' => '2'],
