Comprehensive Guide to String Truncation and Ellipsis Addition in PHP

Nov 27, 2025 · Programming · 9 views · 7.8

Keywords: PHP string processing | string truncation | ellipsis addition

Abstract: This technical paper provides an in-depth analysis of various methods for truncating long strings and adding ellipses in PHP. It covers core functions like substr and mb_strimwidth, compares different implementation strategies, and offers best practices for handling multilingual content and performance optimization in web development scenarios.

Fundamental Requirements and Scenario Analysis for String Truncation

In web development practice, there is often a need to handle long text fields from databases for display on different pages. Typical application scenarios include showing brief description summaries on list pages while displaying full content on detail pages. This requirement necessitates intelligent truncation of overly long strings with ellipsis addition to indicate content truncation.

Detailed Explanation of PHP Core Truncation Functions

Basic Application of substr Function

Using PHP's substr function combined with ternary operators enables basic string truncation functionality:

$out = strlen($in) > 50 ? substr($in, 0, 50) . "..." : $in;

This code first checks the string length using strlen function. If it exceeds 50 characters, it uses substr($in, 0, 50) to extract the first 50 characters and appends an ellipsis; otherwise, it returns the original string directly.

Advanced Application of mb_strimwidth Function

For scenarios requiring more precise control, the mb_strimwidth function can be utilized:

mb_strimwidth("Hello World", 0, 10, "...");

Parameter explanation: the first parameter is the target string, the second parameter is the starting position (0 indicates beginning from the start), the third parameter is the total length after truncation (including the ellipsis), and the fourth parameter is the appended ellipsis string. Note that the third parameter specifies the length including the ellipsis itself.

Multibyte String Processing

When handling strings containing multibyte characters like Chinese, multibyte string functions must be used to avoid character truncation errors:

$truncated = mb_strimwidth($text, 0, 50, "...", "UTF-8");

By specifying the character encoding parameter, correct string truncation can be ensured in multilingual environments.

Intelligent Processing to Avoid Word Truncation

When displaying text excerpts, it's usually necessary to avoid truncating in the middle of words. The following code implements intelligent word boundary truncation:

$text_only_spaces = preg_replace('/\s+/', ' ', $text);
$text_truncated = mb_substr($text_only_spaces, 0, mb_strpos($text_only_spaces, " ", 50));
$preview = trim(mb_substr($text_truncated, 0, mb_strrpos($text_truncated, " ")));

This method first replaces consecutive whitespace characters with single spaces, then finds the first space position after the 50th character for initial truncation, and finally ensures the last word isn't truncated by finding the last space position.

CSS Text Overflow Handling Solution

In addition to server-side PHP processing, CSS can also be used to achieve text overflow with ellipsis display:

.ellipsis {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}

This approach is suitable for fixed-width containers where the browser automatically handles text truncation and ellipsis addition without server-side intervention.

Performance Optimization and Best Practices

In practical applications, appropriate truncation methods should be selected based on specific requirements:

Practical Application Examples

Real-world application example integrated with database queries:

$query = "SELECT description FROM articles WHERE id = ?";
$stmt = $pdo->prepare($query);
$stmt->execute([$article_id]);
$row = $stmt->fetch();

// Use truncated display on list pages
$short_description = mb_strimwidth($row['description'], 0, 50, "...", "UTF-8");

// Display full content on detail pages
$full_description = $row['description'];

By properly applying these techniques, string display requirements across different scenarios can be effectively handled, enhancing user experience and system performance.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.