How can one properly escape special characters in regular expressions when using PHP functions?

When using regular expressions in PHP functions, special characters need to be properly escaped to ensure they are interpreted literally. This can be done by using the preg_quote() function to escape the special characters before using them in the regular expression pattern.

$pattern = '/^[\w\s]+$/'; // Regular expression pattern with special characters
$escaped_pattern = preg_quote($pattern, '/'); // Escape special characters