Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

laravel words()
laravel
php
communitycreator

How to limit the number of words in a string in Laravel?

Chinweuba Elijah Azubuike

Overview

While working with a string, most often we just want to show a paragraph or a few words of the string. Hence, if the site visitor is interested, they click to view more. In this shot, we will learn to achieve this using the words() method.

What is the words() method?

The words() method is one among many methods in Laravel that manipulates strings. The words() method limits the number of words in a string.

Syntax

$string = Str::of('String to be limited')->words(3, ' >>>');

Parameters

The words() method receives two parameters:

  1. The number of words you want to show.
  2. A string you want to append to the end of the limited string.

Code example

Take a look at the file app/Http/Controllers/yourController.php and see line 17 for the usage of the words() method. You can see the result in the Output tab on executing the code below.

<!DOCTYPE html>
<html>
    <?php use App\Http\Controllers\yourController;
    yourController::limitWords(); ?>
</html>

Explanation

In the example above, we import the Illuminate\Support\Str; class. Then, we create a limitWords() function in our controller. We do this in the yourController.php file.

The limitWords() function uses the Str facade which is the Laravel facade for working with strings. We then call the of() method which is a fluent and objectified way that Laravel uses to manipulate strings and chain other string operations.

We pass the whole string we want to limit into the of() method. Then, we chain the words() method and pass the number of words we want to show. In this case, we only want to show the first four words out of the six words in the string. Then, we pass the ‘…’ to make the users know that there is more to show from the string.

Output

When you run the code above, you will see the following output:
Food is a basic....

RELATED TAGS

laravel words()
laravel
php
communitycreator

CONTRIBUTOR

Chinweuba Elijah Azubuike
RELATED COURSES

View all Courses

Keep Exploring