What are the potential pitfalls of using substr() in PHP, especially when dealing with string extraction?
Using substr() in PHP for string extraction can lead to issues if the start or length parameters are not carefully managed. If the start parameter is negative, it can lead to unexpected results. To avoid this, it's important to validate the input parameters before using substr().
// Validate the start and length parameters before using substr()
function safe_substr($string, $start, $length = null) {
if ($start < 0) {
$start = 0;
}
if ($length < 0) {
$length = 0;
}
return substr($string, $start, $length);
}
// Example usage
$string = "Hello, World!";
$start = -5;
$length = 5;
echo safe_substr($string, $start, $length); // Outputs "Hello"