In what ways can the use of preg_quote() be beneficial when working with dynamic values in regex patterns to prevent unexpected results in PHP code?

When working with dynamic values in regex patterns in PHP, it is important to properly escape special characters to prevent unexpected results or security vulnerabilities. The preg_quote() function can be beneficial in this scenario as it automatically escapes special characters in a string, making it safe to use in regex patterns.

$dynamicValue = $_POST['user_input']; // Example of dynamic value from user input
$escapedValue = preg_quote($dynamicValue, '/'); // Escape special characters in the dynamic value

$pattern = '/^' . $escapedValue . '$/'; // Construct regex pattern with escaped dynamic value
if (preg_match($pattern, $input)) {
    // Do something if the input matches the escaped dynamic value
}