Skip to content

Instantly share code, notes, and snippets.

@jongacnik
Created September 27, 2018 23:40
Show Gist options
  • Save jongacnik/b8170a0e4d0ffd63d5acf95118903572 to your computer and use it in GitHub Desktop.
Save jongacnik/b8170a0e4d0ffd63d5acf95118903572 to your computer and use it in GitHub Desktop.

In our builds we often like to have single sentence excerpts. Over the builds I've devised a rather scary looking, but effective, excerpt generating technique:

<?php

// fancy excerpt function which tries to pull 
// the first sentence. minimum character count
// is considered as well.

function trunc($phrase, $max_words) {
  $phrase_array = explode(' ',$phrase);
  if(count($phrase_array) > $max_words && $max_words > 0)
    $phrase = implode(' ',array_slice($phrase_array, 0, $max_words)).'';
  return $phrase;
}

function smartExcerpt ($string) {
  $clean = trim(preg_replace('/\s+/', ' ', strip_tags($string)));
  $parts = preg_split('/(^.*?[a-zA-Z0-9\)\”\"]{2,}[.!?])[\s\”\"]+\W*[A-Z]/', $clean, -1, PREG_SPLIT_DELIM_CAPTURE);
  $parts = array_values(array_filter($parts));
  return (is_array($parts) && isset($parts[0]) && strlen($parts[0]) > 20) 
    ? $parts[0] 
    : trunc($clean, 20);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment