yii\helpers\BaseStringHelper::truncateWords PHP Method

truncateWords() public static method

Truncates a string to the number of words specified.
public static truncateWords ( string $string, integer $count, string $suffix = '...', boolean $asHtml = false ) : string
$string string The string to truncate.
$count integer How many words from original string to include into truncated string.
$suffix string String to append to the end of truncated string.
$asHtml boolean Whether to treat the string being truncated as HTML and preserve proper HTML tags. This parameter is available since version 2.0.1.
return string the truncated string.
    public static function truncateWords($string, $count, $suffix = '...', $asHtml = false)
    {
        if ($asHtml) {
            return static::truncateHtml($string, $count, $suffix);
        }
        $words = preg_split('/(\\s+)/u', trim($string), null, PREG_SPLIT_DELIM_CAPTURE);
        if (count($words) / 2 > $count) {
            return implode('', array_slice($words, 0, $count * 2 - 1)) . $suffix;
        } else {
            return $string;
        }
    }

Usage Example

            <?php 
foreach ($nodes as $node) {
    ?>
                <div class="col-lg-3 col-md-3 col-xs-12 col-sm-3">
                    <div class="blog_inner">
                        <div class="blog-img blog-l">
                            <?php 
    echo \yii\helpers\Html::a(Yii::$app->imageCache->thumb($node->image, '600x400', ['class' => 'img-responsive']), ['review/view', 'slug' => $node->slug]);
    ?>
                        </div>
                        <h2><?php 
    echo \yii\helpers\Html::a($node->title, ['review/view', 'slug' => $node->slug], ['class' => 'info']);
    ?>
</h2>

                        <div class="post-date"><i class="fa fa-calendar"></i> <?php 
    echo date('d-m-Y', $node->updated_at);
    ?>
</div>
                        <p><?php 
    echo \yii\helpers\BaseStringHelper::truncateWords(strip_tags($node->content), 25);
    ?>
</p>
                    </div>
                </div>
            <?php 
}
?>
        </div>
    </div>
</section>
All Usage Examples Of yii\helpers\BaseStringHelper::truncateWords