Skip to content
PHP Logo

What is the function "substr()" used for in PHP and how can it be applied to truncate text output?

The function "substr()" in PHP is used to extract a portion of a string. To truncate text output, you can use this function to limit the number of characters displayed in the output.

php
// Truncate text output using substr()
$text = "This is a long text that needs to be truncated.";
$truncated_text = substr($text, 0, 20) . "..."; // Limit to 20 characters and add ellipsis
echo $truncated_text;