Smart Text Excerpt
Creates sentence-aware excerpts without cutting words or breaking entities.
Function signature
ogCreateSmartExcerpt(text, max_length = 155, suffix = '...')
Categories
- Content Display
Parameters
textSource text or HTML.max_lengthMaximum excerpt length.suffixSuffix added when text is shortened.Return value
Short public-safe status message.
- excerpt
- was_trimmed
- length
Compatibility
Existing function name and call order preserved; metadata signature corrected to source.
Minimum PHP version: 7.4
Security notes
Validate request method, identity, permissions, and caller-owned allowlists before use; keep secrets and internal paths out of public output.
Code
<?php
/*
* Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
* Free for personal and internal use. Paid project use requires visible credit
* to Jeffery L. Paris. Corporate use requires a paid license fee unless a
* separate written license states otherwise.
*/
/**
* Creates a word-safe excerpt from text or HTML content.
*
* The function strips tags, decodes entities, collapses whitespace, and avoids
* cutting through the middle of a word when possible.
*
* @param string $text Source text or HTML.
* @param int $max_length Maximum excerpt length.
* @param string $suffix Suffix added when text is shortened.
* @return array Structured result with excerpt metadata.
*/
function ogCreateSmartExcerpt($text, $max_length = 155, $suffix = '...') {
$result = array(
'success' => false,
'message' => '',
'data' => array()
);
$text = html_entity_decode(strip_tags((string)$text), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
$text = preg_replace('/\s+/', ' ', trim($text));
$max_length = (int)$max_length;
$suffix = (string)$suffix;
if ($max_length < 40) {
$max_length = 40;
}
$was_trimmed = false;
if (strlen($text) <= $max_length) {
$excerpt = $text;
} else {
$limit = $max_length - strlen($suffix);
if ($limit < 20) {
$limit = $max_length;
}
$excerpt = substr($text, 0, $limit);
$last_space = strrpos($excerpt, ' ');
if ($last_space !== false && $last_space > 20) {
$excerpt = substr($excerpt, 0, $last_space);
}
$excerpt = rtrim($excerpt, ' .,;:-') . $suffix;
$was_trimmed = true;
}
$result['success'] = true;
$result['message'] = 'Smart excerpt created.';
$result['data'] = array(
'excerpt' => $excerpt,
'was_trimmed' => $was_trimmed,
'length' => strlen($excerpt)
);
return $result;
}