Truncate text when reach max chars allowed

Aug 08, 2009 Author: Dr_ViRuS

In this tutorial I will show you one simple method how to cut long texts.
This method is really simple.
Method parameters

  • $text - text who we need to check
  • $max_chars - maximum allowed length
  • $end_chars – chars who will be added at end of text
<?php
function truncate_string( $text, $max_chars, $end_chars) {
	$text_len = strlen($text);
	$temp_text = '';
	if ( $text_len > $max_chars) {
		for ($i=0; $i < $max_chars; $i++ ) {
			$temp_text .= $text[$i];
		}
		$temp_text .= $end_chars;
		return $temp_text;
	} else {
		return $text;
	}
}
?>
What do this method?
  • get string length
  • check if text is longer, if is longer create new text variable and return shorter text else return original text
Let's test it!!!
<?php
function truncate_string( $text, $max_chars, $end_chars) {
	$text_len = strlen($text);
	$temp_text = '';
	if ( $text_len > $max_chars) {
		for ($i=0; $i < $max_chars; $i++ ) {
			$temp_text .= $text[$i];
		}
		$temp_text .= $end_chars;
		return $temp_text;
	} else {
		return $text;
	}
}

$text = "Pela  PHP tutorials 2008";
echo truncate_string($text, 3, '...');
?>
Output is:
Pel... 
Note: if you are using UTF-8 u will be have problem with strlen();try with mb_strlen ( string $str [, string $encoding ] ); orwith this strlen(utf8_decode($text)); The utf8_decode($text) will take care of converting the utf characters that have more than one byte in to one symbol and the strlen() will count those correctly as length 1.


views 4043
  1. Add New Comment