Sentence one.
Sentence two.
" collapses to
* "Sentence one.Sentence two." with the two sentences glued together, and
* "" reads as "Item AItem B". This
* inserts a line break at the closing boundary of each block-level tag
* (and at a "
") before stripping, so the stripped text always keeps
* the word boundary the source had, then decodes entities the same way
* {@see \AIPT\Core\ContentStructure\Domain\FieldCatalog}'s own field
* values already do. Every site that turns a description or custom field
* into prompt text should call this instead of a bare
* `wp_strip_all_tags()`, so a future call site cannot reintroduce the gap
* by omission.
*
* @package AIPT\Utils
* @since 2.8.2
*/
namespace AIPT\Utils;
defined( 'ABSPATH' ) || exit;
/**
* Converts stored HTML to prompt-ready plain text.
*/
class HtmlToText {
/**
* Block-level closing tags and line breaks after which the source has a
* word boundary even though `strip_tags()` removes the tag itself with
* no trace. Matched case-insensitively; `
`, `
`, `
` and an
* attributed `
` all match the same alternative.
*/
private const BLOCK_BOUNDARY_PATTERN = '#(?:p|li|div|h[1-6]|tr|td)\s*>|
]*>#i';
/**
* @param string $html Stored HTML (a description, or a custom field that may hold one).
* @return string Plain text: block boundaries kept as a space, entities decoded, whitespace collapsed.
*/
public static function convert( string $html ): string {
if ( '' === trim( $html ) ) {
return '';
}
$with_breaks = (string) preg_replace( self::BLOCK_BOUNDARY_PATTERN, '$0' . "\n", $html );
$text = wp_strip_all_tags( $with_breaks );
$text = html_entity_decode( $text, ENT_QUOTES | ENT_HTML5, 'UTF-8' );
$text = (string) preg_replace( '/\s+/u', ' ', $text );
return trim( $text );
}
}