What are some best practices for effectively utilizing the substr() function in PHP to manipulate strings?

When using the substr() function in PHP to manipulate strings, it is important to understand how the function works and how to effectively utilize its parameters. To extract a portion of a string, you need to provide the string itself, the starting position, and optionally the length of the substring to extract. It is also crucial to handle edge cases such as negative starting positions or lengths that exceed the length of the string.

// Example of utilizing substr() function to extract a portion of a string
$string = "Hello, World!";
$start = 7; // Starting position
$length = 5; // Length of the substring to extract

$substring = substr($string, $start, $length);
echo $substring; // Output: World