A simply function that return a limited words of an input string content based on a max length input parameter. You also can configure the “Read more” text as well as the view detail link. Plus, it automatically detects the closest white space with the max length to avoid cutting your word.
Below is the function definition and example:
1. PHP Show Limited Words Function
<?php
function get_excerpt($content, $max_length, $read_more, $link_detail)
{
if(strlen($content) > $max_length){
$postion = strpos($content, " ", $max_length);
$content = substr($content, 0, $postion);
return $content . " <a href='" . $link_detail . "'>" . $read_more . "</a>";
}
else{
return $content;
}
}
?>
2. Usage
<?php $str = "4 Rapid Development is a technical blog that is targeted at newbie and professional programmers, database administrators, system admin, web masters and bloggers."; echo get_excerpt($str, 30, "Read more", "http://4rapiddev.com/about/"); ?>
Output:
4 Rapid Development is a technical <a href='http://4rapiddev.com/about/'>Read more</a>
