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...

No Comments

Leave a Reply

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

%d bloggers like this: