Cut text dynamically without cut words

I here share other contribution. This is the typically function to cut text to a determinate max number of characters but with the peculiarity that this function not cut words.

For use, only need indicate in the variable $text the text to cut and, in the variable $numMaxChar the number max of characters to show. When the function arrive to this number, him search the last space (in the text cutted) and cut on this point.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
function cutText($text, $numMaxChar){
	if (strlen($text) <  $numMaxChar){
		$textCutted = $text;
	}else{
		$textCutted = substr($text, 0, $numMaxChar);
		$lastSpace = strripos($textCutted, " ");
 
		if ($lastSpace !== false){
			$textCuttedTmp = substr($textCutted, 0, $lastSpace);
			if (substr($textCutted, $lastSpace)){
				$textCuttedTmp .= '...';
			}
			$textCutted = $textCuttedTmp;
		}elseif (substr($text, $numMaxChar)){
			$textCutted .= '...';
		}
	}
 
	return $textCutted;
}

Comment that, if the text to sent not have spaces, the function will cut the text on the max number of characters indicated.

So this function is easy of understand, debug and customizable. I hope you find useful. For any doubt, write the questions on comment box and I try to response as son as possible.

Leave a Reply

Your email address will not be published. Required fields are marked *