73ndcw
Last Updated: February 25, 2016
·
449
· lugat
Dac8182499d9d16703b52d653806840b

Pretty Excerpt

If you want to have a pretty looking excerpt of a longer string, try this function.

Simple add the string, the minimum length, the characters on which the string can be cutted and the extension of the generated excerpt.

function excerpt($string, $minLength = 255, $chars = ' ', $extension = '...')
{

  $length = strlen($string);

  if ($length <= $minLength) {
    return $string;
  }

  $excerptLength = ($length < $minLength) ? 0 : $minLength;

  $pos = null;

  foreach ((array) $chars as $char) {

    $tmp = strpos($string, $char, $excerptLength);

    if ((is_null($pos) || $tmp < $pos) && $tmp) {
      $pos = $tmp + strlen($char);
    }

  }

  $excerpt = is_null($pos) ? substr($string, 0, $excerptLength) : substr($string, 0, $pos);

  return $excerpt.$extension;

}
Say Thanks
Respond

2 Responses
Add your response

14112
D42a7264714dee5006b9c99d2567a320

The problem gets more complex if you have HTML on the input :)

over 1 year ago ·
14113
Dac8182499d9d16703b52d653806840b

HTML and excerpts are always horrible. Anyway you can always define your "chars" on which the function should seperate the string. Some small changes and you will be able to seperate them on HTML-comments like <!-- more -->

over 1 year ago ·