PHP function to cut string into a specific length

PHP function to cut string into a specific length. Very useful for “Read More” links.

function wCut($str, $maxLength = 40) {
$strToCount = html_entity_decode($str);
if (strlen($strToCount) <= $maxLength) {
return $str;
}

$s2 = substr($strToCount, 0, $maxLength - 3);
$s2 .= "...";

return htmlentities($s2);
}

$str = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla nunc risus, euismod ac, facilisis vitae, malesuada in, urna. Sed ut est.';
echo wCut($str); // Lorem ipsum dolor sit amet, consectet...

Tagged with 
About sepedatua
I am nothing special, of this I am sure. I am a common man with common thoughts and I’ve led a common life. There are no monuments dedicated to me and my name will soon be forgotten, but I’ve loved another with all my heart and soul, and to me, this has always been enough.

This site uses Akismet to reduce spam. Learn how your comment data is processed.