" prefix, trim. $markdown = preg_replace( '/\n{3,}/', "\n\n", $markdown ); $markdown = preg_replace( '/^> \s*\n+/m', '> ', $markdown ); $markdown = trim( $markdown ); return $markdown; } /** * Remove Gutenberg block delimiters ( / ). * * Removes ALL HTML comments: Gutenberg markup, editor annotations and * conditional comments. Content between the comments is preserved. * * @param string $html HTML. * @return string */ public static function strip_gutenberg_comments( $html ) { return (string) preg_replace( '@@s', '', $html ); } /** * Remove script/style/iframe/object/embed blocks with their content. * * @param string $html HTML. * @return string */ public static function strip_unsafe_blocks( $html ) { return (string) preg_replace( '@<(script|style|iframe|object|embed|noscript|form)\b[^>]*?>.*?@si', '', $html ); } /** * Convert text pairs to [text](url). * * Runs before whitespace normalization so multi-line link text still * matches. Nested tags inside the link text are flattened later. * * @param string $html HTML. * @return string */ private static function convert_links( $html ) { return (string) preg_replace_callback( '/]*)>(.*?)<\/a\s*>/si', function ( $m ) { $href = self::get_attr( '', 'href' ); $text = $m[2]; if ( '' === $href ) { return $text; // No href: keep just the text. } // Drop markdown-hostile whitespace inside link text. $text = preg_replace( '/\s+/u', ' ', $text ); return '[' . trim( $text ) . '](' . $href . ')'; }, $html ); } /** * Convert ... to ![alt](src). * * @param string $html HTML. * @return string */ private static function convert_images( $html ) { return (string) preg_replace_callback( '/]*)>/si', function ( $m ) { $tag = ''; $src = self::get_attr( $tag, 'src' ); if ( '' === $src ) { return ''; } $alt = self::get_attr( $tag, 'alt' ); // Alt text must not break the Markdown link syntax. $alt = str_replace( array( '[', ']' ), '', $alt ); return '![' . $alt . '](' . $src . ')'; }, $html ); } /** * Collapse whitespace inside text (keeps tag boundaries intact). * * @param string $html HTML. * @return string */ private static function normalize_whitespace( $html ) { // Replace   with a space before whitespace collapsing. $html = str_replace( ' ', ' ', $html ); // Collapse runs of whitespace (incl. newlines between tags) to one space. $html = preg_replace( '/\s+/u', ' ', $html ); return (string) $html; } /** * Core conversion: walk the HTML string tag by tag. * * @param string $html Normalized HTML. * @return string Markdown. */ private static function convert_body( $html ) { $out = ''; $list_stack = array(); // Stack of list contexts: 'ul' | 'ol' with counters. $in_pre = false; // Split into tags and text. $parts = preg_split( '/(<[^>]+>)/', $html, -1, PREG_SPLIT_DELIM_CAPTURE ); foreach ( $parts as $part ) { if ( '' === $part ) { continue; } if ( '<' === $part[0] && strlen( $part ) > 1 && '>' === substr( $part, -1 ) ) { $out .= self::convert_tag( $part, $list_stack, $in_pre ); continue; } // Text node. $text = self::decode_text( $part ); if ( $in_pre ) { $out .= $text; } else { $out .= self::escape_markdown_chars( $text ); } } return $out; } /** * Convert a single tag to Markdown syntax. * * @param string $tag Full tag string, e.g. '

'. * @param array $list_stack Active list stack (modified by reference). * @param bool $in_pre Inside
 flag (modified by reference).
	 * @return string Markdown replacement.
	 */
	private static function convert_tag( $tag, array &$list_stack, &$in_pre ) {
		$is_closing = ( strlen( $tag ) > 1 && '/' === $tag[1] );
		$name_match = array();
		if ( ! preg_match( '# ";

			case 'a':
			case 'img':
				// Already converted in the pre-pass; a stray tag here is dropped.
				return '';

			case 'ul':
			case 'ol':
				if ( $is_closing ) {
					array_pop( $list_stack );
					return "\n";
				}
				$list_stack[] = array( 'type' => $name, 'counter' => 0 );
				return "\n";

			case 'li':
				if ( $is_closing ) {
					return "\n";
				}
				$depth   = max( 0, count( $list_stack ) - 1 );
				$indent  = str_repeat( '  ', $depth );
				$context = end( $list_stack );
				if ( false === $context ) {
					return $indent . '- ';
				}
				if ( 'ol' === $context['type'] ) {
					$list_stack[ count( $list_stack ) - 1 ]['counter']++;
					$marker = $list_stack[ count( $list_stack ) - 1 ]['counter'] . '. ';
				} else {
					$marker = '- ';
				}
				return "\n" . $indent . $marker;

			case 'table':
				return "\n\n";

			case 'thead':
			case 'tbody':
			case 'tfoot':
				return '';

			case 'tr':
				return $is_closing ? "\n" : '| ';

			case 'th':
			case 'td':
				return $is_closing ? ' | ' : '';

			default:
				// Unknown tags: drop the tag, keep content flowing.
				return '';
		}
	}

	/**
	 * Decode a text node for output.
	 *
	 * @param string $text Raw text.
	 * @return string
	 */
	private static function decode_text( $text ) {
		return html_entity_decode( $text, ENT_QUOTES | ENT_HTML5, 'UTF-8' );
	}

	/**
	 * Escape characters that would be interpreted as Markdown syntax
	 * inside plain text runs.
	 *
	 * @param string $text Decoded text.
	 * @return string
	 */
	private static function escape_markdown_chars( $text ) {
		$text = str_replace( '\\', '\\\\', $text );
		$text = preg_replace( '/(?]+)/i';
		if ( ! preg_match( $pattern, $tag, $m ) ) {
			return '';
		}
		if ( isset( $m[2] ) && '' !== $m[2] ) {
			$value = $m[2];
		} elseif ( isset( $m[1] ) && '' !== $m[1] ) {
			$value = $m[1];
		} else {
			$value = $m[0];
		}
		return self::decode_text( $value );
	}
}