Are there any common pitfalls to avoid when working with substr() function in PHP?

One common pitfall when working with the substr() function in PHP is not handling negative values properly. If a negative value is passed as the second argument (length) to substr(), it will count from the end of the string instead of the beginning. To avoid this issue, you can calculate the correct length by subtracting the negative value from the total length of the string.

$string = "Hello, World!";
$substring = substr($string, -6, 5); // This will return "World"
$length = strlen($string) - (-6);
$substring = substr($string, -6, $length); // This will also return "World"