Current Location: Home> Latest Articles> How to Use PHP's substr() Function to Truncate a String and Add Ellipsis

How to Use PHP's substr() Function to Truncate a String and Add Ellipsis

M66 2025-07-27

How to Use PHP's substr() Function to Truncate a String and Add Ellipsis

In PHP development, string truncation is a common requirement, especially when displaying long texts. To keep the user interface clean, it's common to add ellipses at the end of the text. PHP's substr() function provides a simple and efficient way to truncate strings, and when combined with mb_strlen() and mb_substr(), it can handle Chinese characters accurately. In this article, we will demonstrate how to use these functions to truncate strings and add ellipses.

Example Code

Below is a PHP example demonstrating how to create a custom function to truncate a string and append ellipsis:

<?php
function truncateString($string, $length) {
    if (mb_strlen($string, 'utf-8') > $length) {
        $string = mb_substr($string, 0, $length, 'utf-8');
        $string .= '...';
    }
    return $string;
}

// Test example
$text = "Using PHP's substr() function to truncate a string and add ellipsis at the end";
$truncatedText = truncateString($text, 10);
echo $truncatedText;
?>

Code Explanation

In the code above, we define a function named truncateString(). It takes two parameters: the string to be truncated and the desired length. We use mb_strlen() to accurately measure the length of the string, especially for Chinese characters. If the string's length exceeds the specified truncation length, we use mb_substr() to extract a part of the string and append ellipsis to the end.

Test Example

In this example, the original string is "Using PHP's substr() function to truncate a string and add ellipsis at the end", and we set the truncation length to 10. The result is "Using PHP's...", indicating that the excess part of the string has been truncated and represented by ellipsis.

Handling Chinese Characters

In this example, we used mb_strlen() and mb_substr() instead of the regular strlen() and substr() because the mb_ functions handle string length calculations more accurately for Chinese characters. This ensures that the truncation works correctly, avoiding potential errors caused by character encoding differences.

Conclusion

Using PHP's substr() function to truncate strings and add ellipses is a common need in web development. By using mb_strlen() and mb_substr(), we can ensure accurate handling of both English and Chinese characters. If you have similar requirements in your development, you can refer to the example code in this article for a quick solution.