function text_to_paragraphs($text) {
// Normalize line endings
$text = str_replace(["\r\n", "\r"], "\n", $text);
// If the text already contains block-level HTML, do not rewrap those parts.
// Split into chunks of HTML tags vs plain text.
$chunks = preg_split('/(<[^>]+>)/i', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
$output = '';
// HTML block-level elements that should NOT be wrapped in
$blockTags = [
'address','article','aside','blockquote','canvas','dd','div','dl','dt','fieldset',
'figcaption','figure','footer','form','h1','h2','h3','h4','h5','h6',
'header','hr','li','main','nav','noscript','ol','p','pre','section',
'table','tfoot','ul','video'
];
foreach ($chunks as $chunk) {
if (preg_match('/^<([a-z0-9]+)(\s|>)/i', $chunk, $m)) {
// It's an HTML tag; check if it's block-level
if (in_array(strtolower($m[1]), $blockTags)) {
$output .= $chunk;
continue;
}
}
// Otherwise, treat it as text and wrap paragraphs
$paragraphs = array_filter(array_map('trim', explode("\n\n", $chunk)));
foreach ($paragraphs as $p) {
$p = nl2br($p, false); // convert single line breaks to
if ($p !== '') {
$output .= "
$p
";
}
}
}
return $output;
}
Auto para maker
Posted by Mohan on December 7, 2025