Home >Backend Development >PHP Tutorial >How Can I Efficiently Truncate Strings in PHP and Append an Ellipsis?

How Can I Efficiently Truncate Strings in PHP and Append an Ellipsis?

Linda Hamilton
Linda HamiltonOriginal
2024-12-09 16:46:18455browse

How Can I Efficiently Truncate Strings in PHP and Append an Ellipsis?

Truncating Strings in PHP: Trimming and Ellipsis Append

In PHP, efficiently truncating a string to a specified number of characters and appending an ellipsis (...) can be achieved using several methods.

Simple Version:

For a quick truncation, the substr() function can be employed:

$string = substr($string, 0, 10) . '...'; // Truncates to 10 characters

By checking the string's length, we can ensure that the truncated string retains the original length with the ellipsis added:

$string = (strlen($string) > 13) ? substr($string, 0, 10) . '...' : $string; // Truncates to 13 characters (or less)

Functional Approach:

To create a reusable function:

function truncate($string, $length, $dots = "...") {
    return (strlen($string) > $length) ? substr($string, 0, $length - strlen($dots)) . $dots : $string;
}

Advanced Truncation:

To prevent word breaks, the wordwrap() function can be utilized:

function truncate($string, $length = 100, $append = "…") {
    $string = trim($string);

    if (strlen($string) > $length) {
        $string = wordwrap($string, $length);
        $string = explode("\n", $string, 2);
        $string = $string[0] . $append;
    }

    return $string;
}

This function preserves word integrity while truncating the string to the desired length.

The above is the detailed content of How Can I Efficiently Truncate Strings in PHP and Append an Ellipsis?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn