Skip to content
PHP Logo

How can text truncation be implemented in PHP, such as reducing "blablablablabla" to "blabla..."?

To implement text truncation in PHP, you can use the `substr()` function to extract a portion of the original string and then concatenate it with an ellipsis ("...") to indicate that the text has been truncated. You can specify the desired length of the truncated text as well.

php
function truncateText($text, $length) {
    if (strlen($text) > $length) {
        $text = substr($text, 0, $length) . "...";
    }
    return $text;
}

// Example Usage
$text = "blablablablabla";
$truncatedText = truncateText($text, 7);
echo $truncatedText; // Output: blabla...