substr() cuts in the middle of & symbol


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.


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);
$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 Reply

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

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

Google photo

You are commenting using your Google 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 )

Connecting to %s