Skip to content

Instantly share code, notes, and snippets.

@AmrMekkawy
Created March 22, 2015 16:51
Show Gist options
  • Save AmrMekkawy/f1758269f2cf88445eca to your computer and use it in GitHub Desktop.
Save AmrMekkawy/f1758269f2cf88445eca to your computer and use it in GitHub Desktop.
Get specific number of words from a string.
/**
* returns a specific number of words
*
* @param string $string the whole string
* @param integer $num_words number of words to return from the whole string
* @return string returned string
*/
if (!function_exists("brief_text")) {
function brief_text($string, $num_words = 50) {
$string = trim(preg_replace('/\s+/', ' ', $string));
$words = explode(" ", $string);
$required_words = array_slice($words, 0, $num_words); // get sepecific number of elements from the array
return implode(" ", $required_words);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment