How to get first x chars from a string, without cutting off the last word?

Prashant picture Prashant · Jul 9, 2009 · Viewed 16.9k times · Source

I have the following string in a variable.

Stack Overflow is as frictionless and painless to use as we could make it.

I want to fetch first 28 characters from the above line, so normally if I use substr then it will give me Stack Overflow is as frictio this output but I want output as:

Stack Overflow is as...

Is there any pre-made function in PHP to do so, Or please provide me code for this in PHP?

Edited:

I want total 28 characters from the string without breaking a word, if it will return me few less characters than 28 without breaking a word, that's fine.

Answer

Greg picture Greg · Jul 9, 2009

You can use the wordwrap() function, then explode on newline and take the first part:

$str = wordwrap($str, 28);
$str = explode("\n", $str);
$str = $str[0] . '...';