How can regular expressions be used to filter out unwanted characters in PHP?

Regular expressions can be used in PHP to filter out unwanted characters by using the `preg_replace` function. This function allows you to search for a specific pattern of characters and replace them with another set of characters. By defining a regular expression pattern that matches the unwanted characters, you can easily remove them from a string.

// String containing unwanted characters
$string = "Hello, $%^&World!";

// Define regular expression pattern to match unwanted characters
$pattern = '/[^a-zA-Z0-9\s]/';

// Use preg_replace to filter out unwanted characters
$filtered_string = preg_replace($pattern, '', $string);

// Output the filtered string
echo $filtered_string; // Output: Hello World