2

I wan to cut a string in around 300 characters and add "..." at the end if it was above that number of characters. I know it can't be very hard but I don't want to cut a word in half so I wanted to know how do I do it so it doesn't end up like: "And the bird suddenl..."

Thanks

lisovaccaro
  • 32,502
  • 98
  • 258
  • 410

2 Answers2

2
function limit($str, $limit, $append = '...') {
    return preg_replace('/\S*$/', '', mb_substr($str, 0, $limit)) . $append;
}
Vojta
  • 23,061
  • 5
  • 49
  • 46
2

http://php.net/wordwrap

$str = 'A very long string here';
$str = wordwrap($str, 100);
$str = explode("\n", $str);
$str = $str[0] . '...';
Naveed
  • 41,517
  • 32
  • 98
  • 131
  • Nope. Try with `"is simply dummy \ntext of the printing and"` – Gordon Jan 23 '11 at 17:23
  • We can use `$str = str_replace("\n",'',$str);` at the beginning... Is it ?? – Naveed Jan 23 '11 at 17:33
  • What if the OP wants to stay newlines intact? You dont know if the resulting string is printed in a browser where newlines are not shown anyway. It could be printed in a shell environment and there it would be meaningful. – Gordon Jan 23 '11 at 17:37
  • OP may want many other things also. OP is allowed to play with this solution. – Naveed Jan 23 '11 at 17:42