How to truncate a string to a given length
Short answer
Take the required number of characters with mb_substr() and add an ellipsis if the string was longer. mb_strlen() checks the length:
<?php
$text = 'A very long article title';
$limit = 13;
echo mb_strlen($text) > $limit ? mb_substr($text, 0, $limit) . '…' : $text;Output:
A very long a…A built-in function
mb_strimwidth() truncates a string to a given width. That width includes the trim marker itself:
<?php
echo mb_strimwidth('A very long article title', 0, 14, '…');Output:
A very long a…