Are there any potential pitfalls to be aware of when using substr() in PHP?

One potential pitfall to be aware of when using substr() in PHP is that if the start parameter is a negative number, it counts from the end of the string instead of the beginning. This can lead to unexpected results if not handled properly. To avoid this issue, always ensure that the start parameter is a positive number or use strlen() to calculate the correct index when using negative numbers.

$string = "Hello, World!";
$start = -5;
$length = 5;

if ($start < 0) {
    $start = strlen($string) + $start;
}

$substring = substr($string, $start, $length);

echo $substring; // Outputs "World"