*/ public static function collect( string $content, int $max_level = 3 ): array { $rendered = self::strip_blocks( $content ); if ( ! preg_match_all( '/]*)>(.*?)<\/h\1>/is', $rendered, $matches, PREG_SET_ORDER ) ) { return array(); } $out = array(); $seen = array(); foreach ( $matches as $match ) { $level = (int) $match[1]; if ( $level > $max_level ) { continue; } $text = trim( wp_strip_all_tags( $match[3] ) ); if ( '' === $text ) { continue; } $out[] = array( 'level' => $level, 'text' => $text, 'id' => self::anchor( $text, $match[2], $seen ), ); } return $out; } /** * Add the ids to the rendered content, matching what collect() linked to. * * Only headings that have no id of their own are touched: an editor who * typed an anchor meant it, and a link somewhere else may already use it. */ public static function add_ids( string $html ): string { $seen = array(); return (string) preg_replace_callback( '/]*)>(.*?)<\/h\1>/is', static function ( array $m ) use ( &$seen ): string { $text = trim( wp_strip_all_tags( $m[3] ) ); if ( '' === $text ) { return $m[0]; } $id = self::anchor( $text, $m[2], $seen ); if ( preg_match( '/\sid\s*=\s*["\']/i', $m[2] ) ) { return $m[0]; } return '' . $m[3] . ''; }, $html ); } /** * @param array $seen By reference: how often this slug was used. */ private static function anchor( string $text, string $attributes, array &$seen ): string { if ( preg_match( '/\sid\s*=\s*["\']([^"\']+)["\']/i', $attributes, $m ) ) { return sanitize_title( $m[1] ); } $slug = sanitize_title( $text ); if ( '' === $slug ) { $slug = 'section'; } $seen[ $slug ] = ( $seen[ $slug ] ?? 0 ) + 1; return $seen[ $slug ] > 1 ? $slug . '-' . $seen[ $slug ] : $slug; } /** Block comments are not headings; strip them before matching. */ private static function strip_blocks( string $content ): string { return (string) preg_replace( '//s', '', $content ); } }