What are the potential pitfalls of using the preg_replace function in PHP for search queries?

One potential pitfall of using the preg_replace function for search queries is that it can be vulnerable to regex injection attacks if user input is not properly sanitized. To prevent this, it is important to use a whitelist approach to only allow certain characters or patterns in the regex pattern.

// Sanitize user input before using it in preg_replace
$user_input = $_GET['search_query'];
$whitelisted_pattern = '/^[a-zA-Z0-9\s]+$/'; // Allow only letters, numbers, and spaces

if (preg_match($whitelisted_pattern, $user_input)) {
    $sanitized_input = preg_replace('/[^a-zA-Z0-9\s]/', '', $user_input);
    // Use $sanitized_input in preg_replace or other functions
} else {
    // Handle invalid input error
}