Skip to content

Instantly share code, notes, and snippets.

@iboved
Last active July 10, 2020 12:43
Show Gist options
  • Save iboved/905f9fb75d84559343013c441f32b378 to your computer and use it in GitHub Desktop.
Save iboved/905f9fb75d84559343013c441f32b378 to your computer and use it in GitHub Desktop.
Laravel | Limit the number of characters in a string and leave the full word at the end.

Description:

Limit the number of characters in a string and leave the full word at the end using the Laravel Framework. In other words, do not cut the word at the end of the line. Assume the only requirement is "limit+ character string that is composed of full words".

Algorithm:

  1. Call Str::limit($limit) and save the result.
  2. Count words in that result.
  3. Call Str::words() to get that number of words from the original string.

Example:

$limit = 20;
$original = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed pharetra.';
$new = \Str::words($original, str_word_count(\Str::limit($original, $limit)));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment