phpstringellipsistruncation

Truncate a string to first n characters of a string and add three dots if any characters are removed


How can I get the first n characters of a string in PHP? What's the fastest way to trim a string to a specific number of characters, and append '...' if needed?


Solution

  • To truncate the string after a set number of characters:

    <?php
    
    /**
     * @param string      $text          The text to shorten.
     * @param int         $limit         Max characters **including** the suffix. Must be ≥ 1.
     * @param string      $suffix        What to append when truncated (default: ellipsis).
     * @param bool        $preserveWords Try not to cut a word in half.
     * @param string|null $encoding      Explicit multibyte encoding (null = mb_internal_encoding()).
     *
     * @throws InvalidArgumentException  If $limit is less than 1.
     */
    function truncate(
        string $text,
        int $limit = 100,
        string $suffix = '…',
        bool $preserveWords = true,
        ?string $encoding = null
    ): string {
        if ($limit < 1) {
            throw new InvalidArgumentException('$limit must be at least 1');
        }
    
        $encoding ??= mb_internal_encoding();
        $suffixLen = mb_strlen($suffix, $encoding);
    
        if ($suffixLen >= $limit) {
            return mb_substr($suffix, 0, $limit, $encoding);
        }
    
        if (mb_strlen($text, $encoding) <= $limit) {
            return $text;
        }
    
        $cut = $limit - $suffixLen;
        $snippet = mb_substr($text, 0, $cut, $encoding);
    
        if ($preserveWords) {
            $result = preg_replace('/\s+\S*$/u', '', $snippet);
            
            // If preg_replace fails, $snippet remains unchanged
            if (is_string($result)) {
                 $snippet = $result;
            }
        }
    
        return rtrim($snippet) . $suffix;
    }
    

    Note: This function uses the Multibyte String functions in PHP so ensure the mbstring extension is enabled.