Prashant Prashant - 7 months ago 28
PHP Question

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

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?


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.


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] . '...';