Truncate string with PHP

It’s very simple, but useful; for instance, when you make a listing of articles on a page, but you only want to display a preview of the content of each article. Here is a small PHP function for text truncation :

function truncate_text($text, $nbrChar, $append=’…’) {
if(strlen($text) > $nbrChar) {
$text = substr($text, 0, $nbrChar);
$text .= $append;
}
return $texte;
}

// Now, we apply the function to a text :
echo truncate_text(‘this is a text I\’d like to truncate at fifty characters’, 50);

// which will have as result :
// this is a text I’d like to truncate at fifty cha…

Ce message est également disponible en : French

6 thoughts on “Truncate string with PHP

  1. Frankie Jarrett

    Thank you for this handy little function! 🙂

    I made a few adjustments to make it workable as a global WordPress function.

    For all you WordPressers out there, just add this to your functions.php file:


    function truncate_text($text, $nbrChar = null, $append = ' ...') {
    if(strlen($text) > $nbrChar) {
    $text = substr($text, 0, $nbrChar);
    $text .= $append;
    }
    return $text;
    }
    add_action('init', 'truncate_text');

    //Frankie

Leave a Reply

Your email address will not be published. Required fields are marked *