Truncate And Limit Displayed Text With Selected Maximum Length PHP Function
Posted by in PHP May 28, 2011 Leave a comment

The PHP function below truncates a string to the number of characters specified. It maintains the integrity of words so the character count may be slightly more or less than what you specify. Or in other words, it limits the displayed text length on your web page then generates a link to a page to read the full content if its bigger than the selected maximum length.

It’s useful when you pull your articles from database of a particular CMS (Content Management System) and display them on the Homepage or Category Pages. If the content is too long, it may break your page layout.

1. PHP function: Character Limiter

<?php
	function character_limiter($str, $detail_link, $maximum_characters = 500, $end_char = '&#8230;')
	{
		if (strlen($str) < $maximum_characters)
		{
			return $str;
		}
 
		$str = preg_replace("/\s+/", ' ', str_replace(array("\r\n", "\r", "\n"), ' ', $str));
 
		if (strlen($str) <= $maximum_characters)
		{
			return $str;
		}
 
		$out = "";
		foreach (explode(' ', trim($str)) as $val)
		{
			$out .= $val.' ';
			if (strlen($out) >= $maximum_characters)
			{
				return trim($out) . " <a href='" . $detail_link . "' title='Read more'>" . $end_char . "</a>";
			}
		}
	}
?>

2. Usage

<?php
	$str = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";
 
	echo character_limiter($str, "http://www.lipsum.com/", 149);
?>

3. Output in HTML code

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, <a href='http://www.lipsum.com/' title='Read more'>&#8230;</a>

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