Skip to content

Instantly share code, notes, and snippets.

@mykebates
Created April 22, 2012 02:34
Show Gist options
  • Select an option

  • Save mykebates/2442029 to your computer and use it in GitHub Desktop.

Select an option

Save mykebates/2442029 to your computer and use it in GitHub Desktop.
Trim excerpt without incomplete words
function excerpt_char($text, $lim, $delim="…")
{
$len = strlen($text);
if ($len <= $lim) return $text;
// split at first word boundary after $lim chars
preg_match('/(.{' . $lim . '}.*?)\b/', $text, $matches);
$text = preg_replace("'(&[a-zA-Z0-9#]+)$'", '$1;', $matches[1]);
$text .= $delim;
return $text;
}
// Can pass in WordPress excerpt like this - echo excerpt_char(get_the_excerpt(), 200);
// This will limit the excerpt to around 200 characters and will not leave you with an incomplete word.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment