esedic
2/18/2016 - 2:29 PM

Truncate string with PHP - keep full words and static cut

Truncate string with PHP - keep full words and static cut

<?php 
  $string = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi semper sagittis nulla, et egestas lectus tincidunt eu. Donec vehicula erat id sagittis pulvinar.';
  // 1. keeps full words
  if(strlen($string) > 100) {
    echo preg_replace('/\s+?(\S+)?$/', '', substr($string, 0, 101)).'...';
  }

  //2. cuts words when character limit reached
  if (strlen($string) > 100) {
    echo substr($string, 0, 100). "...";
  }
?>