What are some common errors to watch out for when using substr() in PHP to manipulate file names?

When using substr() in PHP to manipulate file names, a common error to watch out for is not accounting for the length of the file extension. This can lead to unexpected results or errors when trying to extract or modify the file name. To avoid this issue, it's important to calculate the length of the file extension and adjust the substr() parameters accordingly.

// Example code snippet to correctly manipulate file names using substr()

$filename = "example.jpg";
$extension_length = strlen(pathinfo($filename, PATHINFO_EXTENSION));

// Extract file name without extension
$file_without_extension = substr($filename, 0, -($extension_length + 1));

// Modify file name
$new_filename = $file_without_extension . "_new." . pathinfo($filename, PATHINFO_EXTENSION);

echo $new_filename;