How do You Truncate a String to a Certain Length in PHP?

Hello Friends Today, through this tutorial, I will tell you How do you truncate a string to a certain length in PHP With Example? In PHP, you can truncate a string to a certain length using the `substr()` function. Here’s how you can do it:

<?php
function truncateString($string, $maxLength) {
if (strlen($string) > $maxLength) {
$string = substr($string, 0, $maxLength) . "...";
}
return $string;
}

// Example usage:
$string = "This is a long string that needs to be truncated.";
$maxLength = 20;
$truncatedString = truncateString($string, $maxLength);
echo $truncatedString; // Output: "This is a long strin..."
?>

In this example, the `truncateString()` function takes two parameters: the input string `$string` and the maximum length `$maxLength` to which the string should be truncated. Inside the function, it checks if the length of the input string exceeds the maximum length. If it does, it uses `substr()` to extract a substring from the beginning of the input string up to the maximum length, and appends “…” to indicate that the string has been truncated. Finally, it returns the truncated string.