limit() and words()

Truncate long text by characters or by words.

Syntax\Illuminate\Support\Str::limit($text, 100, '...');

The Str::limit() method truncates a string to a number of characters and adds an ellipsis. The Str::words() method truncates to a number of words instead.

You can customize the trailing string with the last argument.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • A news feed trims article body text to 160 characters with Str::limit() to fit the preview card without overflowing its container.
  • A social platform uses Str::words() to cut a user bio to 20 words for the compact profile widget while preserving word boundaries.
  • An email template shortens long product names to 50 characters before injecting them into the subject line to avoid truncation by email clients.

More examples

Truncate by character count

Str::limit() cuts the string at 40 characters and appends '...' (the default suffix) automatically.

Example · php
use Illuminate\Support\Str;

$body = 'Laravel is a web application framework with expressive syntax.';

$preview = Str::limit($body, 40);
// => 'Laravel is a web application framework...'

Custom ellipsis and word truncation

Shows how to override the trailing suffix in Str::limit() and how Str::words() respects word boundaries instead of raw character positions.

Example · php
use Illuminate\Support\Str;

// Custom end string
$preview = Str::limit('The quick brown fox', 15, ' [more]');
// => 'The quick brown [more]'

// Truncate by word count
$bio = Str::words('One two three four five six', 4);
// => 'One two three four...'

Limit post titles in a Blade loop

Maps a collection of posts to shape data for display, limiting the title to 60 characters and the body to 20 words for each card.

Example · php
// In a controller
$posts = Post::latest()->take(10)->get()->map(fn($p) => [
    'id'      => $p->id,
    'title'   => Str::limit($p->title, 60),
    'excerpt' => Str::words($p->body, 20),
]);

return view('posts.index', compact('posts'));

Discussion

  • Be the first to comment on this lesson.