Yii2 how to trim string - StringHelper
Last updated: Jul 24, 2022
Colleagues hello to all.
In today's small article, I'll show you how to cut a string very quickly and easily in Yii2. Of course, you can cut the string using the php language itself, but if the framework provides us with such an opportunity, then why not use it.
In order for us to trim strings in Yii2, we need to use the built-in class called StringHelper. In the StringHelper class, we are interested in two methods, truncate() and truncateWords().
The first method is truncateWords().
$truncate = \yii\helpers\StringHelper::truncateWords($title, 10, '...');
This method truncates a string to the specified number of words. We have indicated that we want 10 words in our line, and the rest is hidden.
The second parameter is truncate().
$truncate = \yii\helpers\StringHelper::truncate($title, 50, ' ...');
This method truncates a string to the specified number of characters. We have indicated that we want 50 characters in our line, and the rest is hidden.
Thank you all, I hope that my article helped you in some way.