user2331090
user2331090

Reputation: 279

How can I truncate a string in php without cutting off words?

Im looking for a soluting for the followting case. I have a string

"This is a long string of words"

I want to use only the first few words, but if I just cut everything after 20th character, it will look like this:

"This is a long strin"

I can grab first 3 words

implode(' ', array_slice(explode(' ', "This is a long string of words"), 0, 3));

But in some cases, 3 words are going to be too short "I I I".

How can I grab as many words as possible before 20th character?

Upvotes: 3

Views: 1863

Answers (2)

Rob
Rob

Reputation: 12872

echo array_shift(explode("\n", wordwrap($text, 20)));

Documentation:

Upvotes: 7

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324600

Before I give you an answer in PHP, have you considered the following CSS solution?

overflow:hidden;
white-space:nowrap;
text-overflow:ellipsis;

This will result in the text being cut off at the most appropriate place and an ellipsis ... marking the cut-off.

If this is not the effect you're looking for, try this PHP:

$words = explode(" ",$input);
// if the first word is itself too long, like hippopotomonstrosesquipedaliophobia‎
// then just cut that word off at 20 characters
if( strlen($words[0]) > 20) $output = substr($words[0],0,20);
else {
    $output = array_shift($words);
    while(strlen($output." ".$words[0]) <= 20) {
        $output .= " ".array_shift($words);
    }
}

Upvotes: 2

Related Questions