What is the function in PHP that can be used to truncate a string to a certain length?

When working with strings in PHP, you may need to truncate a string to a certain length for various reasons such as displaying a preview of a longer text. The `substr()` function in PHP can be used to achieve this by specifying the start position and the length of the substring you want to extract.

// Truncate a string to a certain length
function truncateString($string, $length) {
    if(strlen($string) > $length) {
        $string = substr($string, 0, $length);
        $string .= "...";
    }
    return $string;
}

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