<?php

/**
 * Strip HTML from a writer/rich-text field while preserving readable whitespace.
 * Block-level elements (p, li, br, headings, hr, div) are replaced with newlines
 * before the tags are removed, so words never run together.
 */
function writerToPlainText(string $html): string
{
    // Replace block-level closing/self-closing tags with a newline
    $text = preg_replace(
        '/<\\/?(p|li|br|h[1-6]|hr|div|blockquote|tr)[^>]*>/i',
        "\n",
        $html
    );

    // Drop all remaining tags
    $text = strip_tags($text);

    // Decode HTML entities (e.g. &amp; → &)
    $text = html_entity_decode($text, ENT_QUOTES | ENT_HTML5, 'UTF-8');

    // Collapse runs of blank lines to a single blank line, trim edges
    $text = preg_replace("/\n{3,}/", "\n\n", $text);

    return trim($text);
}
