PHP: How to truncate characters and words…

Posted on January 9, 2012 by Jimmy K. in Tutorials.

Sometimes you just need to shorten that huge wall of text. Here are two functions that I use frequently to limit the display of lengthy user input:

<?php

/* truncate input by chars. */
function jTruncate($sInput, $iMaxChars = 10, $sCapText = "...") {

	if (strlen($sInput) > $iMaxChars) {
		$sInput = substr($sInput, 0, $iMaxChars) . $sCapText;
	}

	return $sInput;

}

/* truncate input by words. */
function jTruncateWords($sInput, $iMaxWords = 10, $sCapText = "...") {

	$aInput = explode(" ", $sInput);
	$sOutput = "";

	for ($i = 0; $i < sizeof($aInput); $i++) {
		if ($i < $iMaxWords) $sOutput .= (!empty($sOutput) ? " " : "") . $aInput[$i];
	}

	if (sizeof($aInput) > $iMaxWords) {
		$sOutput .= $sCapText;
	}

	return $sOutput;

}

?>

The first function, jTruncate(), truncates text if it is greater than the specified number of characters. For example, if you pass “This is a large block of text!” with a character limit of 12, it will become “This is a lar…”

The second function, jTruncateWords(), does the same thing except it’s based on words instead of characters. For example, if you pass “This is a large block of text!” with a word limit of 4, it will become “This is a large…”

Tags: , , ,

 
 
 

If you like this, please leave a comment.