Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get first 100 characters from string, respecting full words

Tags:

string

php

I have asked a similar question here before, but I need to know if this little tweak is possible. I want to shorten a string to 100 characters and use $small = substr($big, 0, 100); to do so. However, this just takes the first 100 characters and doesn't care whether it breaks up a word or not.

Is there any way to take up to the first 100 characters of a string but make sure you don't break a word?

Example:

$big = "This is a sentence that has more than 100 characters in it, and I want to return a string of only full words that is no more than 100 characters!"  $small = some_function($big);  echo $small;  // OUTPUT: "This is a sentence that has more than 100 characters in it, and I want to return a string of only" 

Is there a way to do this using PHP?

like image 818
JoshFinnie Avatar asked Jun 09 '09 19:06

JoshFinnie


1 Answers

All you need to do is use:

$pos=strpos($content, ' ', 200); substr($content,0,$pos );  
like image 125
amir Avatar answered Sep 19 '22 23:09

amir