diff --git a/src/Components/Blocks/Header.php b/src/Components/Blocks/Header.php
index 3a50a66..615937d 100644
--- a/src/Components/Blocks/Header.php
+++ b/src/Components/Blocks/Header.php
@@ -68,7 +68,12 @@ final class Header implements Block
$text = \trim($text, " \t");
# remove closing sequence
- $text = \rtrim(\rtrim($text, '#'), " \t");
+ $removedClosing = \rtrim($text, '#');
+ $lastChar = \substr($removedClosing, -1, 1);
+
+ if (\trim($lastChar, " \t") === '') {
+ $text = \rtrim($removedClosing, " \t");
+ }
return new self($text, $level);
}
diff --git a/tests/commonmark/45-ATX_headings.html b/tests/commonmark/45-ATX_headings.html
new file mode 100644
index 0000000..3c9245b
--- /dev/null
+++ b/tests/commonmark/45-ATX_headings.html
@@ -0,0 +1 @@
+
foo#
\ No newline at end of file
diff --git a/tests/commonmark/45-ATX_headings.md b/tests/commonmark/45-ATX_headings.md
new file mode 100644
index 0000000..5037128
--- /dev/null
+++ b/tests/commonmark/45-ATX_headings.md
@@ -0,0 +1 @@
+# foo#
\ No newline at end of file
diff --git a/tests/commonmark/46-ATX_headings.html b/tests/commonmark/46-ATX_headings.html
new file mode 100644
index 0000000..43d06bd
--- /dev/null
+++ b/tests/commonmark/46-ATX_headings.html
@@ -0,0 +1,3 @@
+foo ###
+foo ###
+foo #
\ No newline at end of file
diff --git a/tests/commonmark/46-ATX_headings.md b/tests/commonmark/46-ATX_headings.md
new file mode 100644
index 0000000..a14fd9f
--- /dev/null
+++ b/tests/commonmark/46-ATX_headings.md
@@ -0,0 +1,3 @@
+### foo \###
+## foo #\##
+# foo \#
\ No newline at end of file