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
Release: 2024-12-09 16:46:18
Original
459 people have browsed it

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
Copy after login

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)
Copy after login

Functional Approach:

To create a reusable function:

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

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template