Skip to content
PHP Logo

How can PHP functions like ereg_replace or preg_replace be utilized to address text truncation issues?

Text truncation issues can be addressed using PHP functions like ereg_replace or preg_replace by specifying a pattern to match the text that needs to be truncated and replacing it with an ellipsis or a shortened version of the text. This allows for custom truncation rules to be applied to text, ensuring that it fits within a specified length limit.

php
function truncate_text($text, $limit) {
    if (strlen($text) > $limit) {
        $text = preg_replace('/\s+?(\S+)?$/', '', substr($text, 0, $limit+1)) . '...';
    }
    return $text;
}

$text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
$truncated_text = truncate_text($text, 20);
echo $truncated_text;