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.

Advertisements

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 Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s