What is the purpose of the PHP function "substr" and how can it be used to truncate a string?

The purpose of the PHP function "substr" is to extract a portion of a string. To truncate a string using the "substr" function, you can specify the starting position and the length of the substring you want to extract.

$string = "This is a long string that needs to be truncated";
$truncated_string = substr($string, 0, 20);
echo $truncated_string; // Output: "This is a long stri"