substr() cuts in the middle of & symbol

Description:

In “Read more” segments, you often need to cut the text to a length and add ‘…’ at the end. This can be a bit tricky when the limit falls on a special character.

Solution:

We can use mb_substr() instead, and first decode the text and set the “UTF-8” charset:

$length = 40;
$padding = ‘…’;

if (strlen($fullDescription) > ($length + 3)) {
$shortDescription = html_entity_decode($fullDescription);
mb_internal_encoding(“UTF-8”);
$shortDescription = mb_substr($shortDescription, 0, $length);
$shortDescription  .= $padding;
}

This will decode all entities into their natural symbol and make sure they are interpreted as one character.

About admin

Just another php developer trying to give something back to the community.
This entry was posted in Best practices, PhP and tagged , , , , . Bookmark the permalink.

Leave a comment