PHP Show Limited Words Of A String Content Based On Max Length
Posted by in PHP August 25, 2011 1 Comment

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>

Hoan Huynh is the founder and head of 4rapiddev.com. Reach him at hoan@4rapiddev.com
  • paraz

    thank a lot… it works properly.. but if you are explaining the code then it would be better..
    thanks again :)