How can regular expressions be used in PHP to replace invalid characters in filenames with underscores?

When dealing with filenames, it's important to ensure that they do not contain any invalid characters that could cause issues. Regular expressions can be used in PHP to search for and replace these invalid characters with underscores. By using a regular expression pattern that matches invalid characters and the `preg_replace()` function, we can easily sanitize filenames.

$filename = "file*name.txt";
$clean_filename = preg_replace('/[^\w\s-]/', '_', $filename);
echo $clean_filename;
// Output: file_name.txt