tags from HTML, replacing each with a unique placeholder. * * @param string $content Raw HTML content (may contain zero or more tags). * @param int $startIndex Starting index for placeholder numbering. * @return array{content: string, imageMap: array} HTML with placeholders and image map. * * @since 2.5.13 */ public static function mask( string $content, int $startIndex = 0 ): array { $imageMap = array(); $counter = $startIndex; $maskedContent = preg_replace_callback( '/]*\/?>/is', function ( $matches ) use ( &$imageMap, &$counter ) { $placeholder = '##AIPT_IMG_' . $counter . '##'; $imageMap[ $placeholder ] = $matches[0]; $counter++; return $placeholder; }, $content ); if ( null === $maskedContent ) { return array( 'content' => $content, 'imageMap' => array(), ); } return array( 'content' => $maskedContent, 'imageMap' => $imageMap, ); } /** * Restore tags from placeholders. Handles dropped placeholders via fallback append. * * @param string $content AI response content containing placeholders. * @param array $imageMap Placeholder => tag map from mask(). * @return array{content: string, restored: int, missing: array} Restored content metadata. * * @since 2.5.13 */ public static function unmask( string $content, array $imageMap ): array { $restored = 0; $missing = array(); foreach ( $imageMap as $placeholder => $imageTag ) { if ( false !== strpos( $content, $placeholder ) ) { $content = str_replace( $placeholder, $imageTag, $content ); $restored++; continue; } $missing[] = $placeholder; } if ( ! empty( $missing ) ) { $missingImages = array(); foreach ( $missing as $placeholder ) { if ( isset( $imageMap[ $placeholder ] ) ) { $missingImages[] = $imageMap[ $placeholder ]; } } $content .= "\n\n

\n" . implode( "\n", $missingImages ) . "\n

"; } return array( 'content' => $content, 'restored' => $restored, 'missing' => $missing, ); } }