Skip to content
Advertisement

How can I truncate a string to the first 20 words in PHP?

How can I truncate a string after 20 words in PHP?

Advertisement

Answer

function limit_text($text, $limit) {
    if (str_word_count($text, 0) > $limit) {
        $words = str_word_count($text, 2);
        $pos   = array_keys($words);
        $text  = substr($text, 0, $pos[$limit]) . '...';
    }
    return $text;
}

echo limit_text('Hello here is a long sentence that will be truncated by the', 5);

Outputs:

Hello here is a long ...
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement