Hi, Guest!

Custom PHP exerpt() function

30-05-2010 php Roumen


This is an example for custom PHP excerpt() function, returning numbers of characters from longer text. It gets two parameters, text and number of characters to return, it removes html tags and returns only text.

It works without problems with multibyte encoding like UTF-8, because uses mb_substr instead of substr and counts number of simbols instead of number of bytes.

To the result automatically is concatenated two dots for better reading.

function excerpt($content,$maxchars=50){
   $content = mb_substr(strip_tags($content), 0, $maxchars,'UTF-8');
   return $content . '.. ';

Example for usage:

<?php echo excerpt($post->body,120), '<a href="blog">more &raquo;</a>' ?>