How can a PHP variable be truncated to a specific number of characters?

To truncate a PHP variable to a specific number of characters, you can use the substr() function. This function allows you to extract a portion of a string based on a specified start position and length. By using substr() on the variable and specifying the desired length, you can effectively truncate the variable to the desired number of characters.

$originalString = "This is a long string that needs to be truncated.";
$truncatedString = substr($originalString, 0, 20); // Truncate to 20 characters

echo $truncatedString; // Output: "This is a long stri"