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!