3

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?

4
  • What language are you using? C++, Java, C#, Php? Commented Jul 6, 2013 at 22:14
  • oh, I didnt mention, php Commented Jul 6, 2013 at 22:16
  • 1
    You can use regular expressions, or you can search for the space between words and use the split command to generate an array of words. Commented Jul 6, 2013 at 22:17
  • Try This Link, May help You... stackoverflow.com/a/26098951/3944217 Commented Sep 29, 2014 at 12:07

2 Answers 2

7

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

Documentation:

Sign up to request clarification or add additional context in comments.

1 Comment

Added some documentation links. +1 for using a function I'd forgotten about XD
2

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); } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.