Чтобы избежать обрезки прямо в середине слова, вы можете попробовать функцию wordwrap
; что-то вроде этого, я полагаю, может сделать:
$str = "this is a long string that should be cut in the middle of the first 'that'";
$wrapped = wordwrap($str, 25);
var_dump($wrapped);
$lines = explode("\n", $wrapped);
var_dump($lines);
$new_str = $lines[0] . '...';
var_dump($new_str);
$wrapped
будет содержать:
string 'this is a long string
that should be cut in the
middle of the first
'that'' (length=74)
Массив $lines
будет выглядеть так:
array
0 => string 'this is a long string' (length=21)
1 => string 'that should be cut in the' (length=25)
2 => string 'middle of the first' (length=19)
3 => string ''that'' (length=6)
И, наконец, ваш $new_string
:
string 'this is a long string' (length=21)
С подстроном, вот так:
var_dump(substr($str, 0, 25) . '...');
Вы бы получили:
string 'this is a long string tha...' (length=28)
Что выглядит не так красиво: - (
Тем не менее, получайте удовольствие!