In PHP, what functions or methods can be used to replace invalid characters in a string with underscores for file naming purposes?

When creating files, it's important to ensure that the file names are valid and do not contain any characters that could cause issues. To replace invalid characters in a string with underscores for file naming purposes, you can use the `preg_replace()` function in PHP. This function allows you to search for a pattern in a string and replace it with a specified value, such as an underscore.

// String with invalid characters
$string = "file*name.txt";

// Replace invalid characters with underscores
$cleaned_string = preg_replace('/[^\w.-]/', '_', $string);

echo $cleaned_string; // Output: file_name.txt