Magento 2 truncate string to specific limit.

Magento 2 You can truncate the string using Magento best practice.

By default, You can truncate the string using substr() PHP method.

Magento gives Out of the box feature for a truncate string using Magento\Framework\Stdlib\StringUtils class.

You need to use StringUtils class with constructor dependency injection to substring or truncate the string.

<?php
public function __construct(
    \Magento\Framework\Stdlib\StringUtils $string
) {
    $this->string = $string;
}

public function getTruncateString()
{
    $stringValue = "This string needs to truncate";
    $result = $this->string->substr($stringValue, 0, 11);
    return $result;
}

You can get the result by calling function,

echo $this->getTruncateString();

Output:
This string (first 11 characters)

The Result will be only the first 11 characters from “This string needs to truncate”. Above method works the same as substr() method of core PHP.