Tuesday 2 June 2015

Get excerpt from string - Get excerpt from string

<?php

/**
 * Get excerpt from string
 * 
 * @param String $str String to get an excerpt from
 * @param Integer $startPos Position int string to start excerpt from
 * @param Integer $maxLength Maximum length the excerpt may be
 * @return String excerpt
 */
function getExcerpt($str, $startPos=0, $maxLength=100) {
 if(strlen($str) > $maxLength) {
  $excerpt   = substr($str, $startPos, $maxLength-3);
  $lastSpace = strrpos($excerpt, ' ');
  $excerpt   = substr($excerpt, 0, $lastSpace);
  $excerpt  .= '...';
 } else {
  $excerpt = $str;
 }
 
 return $excerpt;
}

?>

Usage

$excerpt = getExcerpt($longText, 0, 150);
 

0 comments:

Post a Comment