What potential pitfalls should be considered when using regex patterns stored in a database with PHP's preg_match function?

When using regex patterns stored in a database with PHP's preg_match function, a potential pitfall to consider is the security risk of executing arbitrary code if the patterns are not properly sanitized. To mitigate this risk, always ensure that the regex patterns retrieved from the database are sanitized and validated before using them in the preg_match function. This can be done by using a whitelist approach to only allow specific, safe regex patterns to be stored in the database.

// Retrieve regex pattern from the database
$pattern = retrieve_pattern_from_database();

// Sanitize and validate the regex pattern
$allowed_patterns = ['/^[a-zA-Z0-9]+$/'];
if (in_array($pattern, $allowed_patterns)) {
    // Use the sanitized regex pattern in preg_match
    if (preg_match($pattern, $input)) {
        // Regex pattern matched
    } else {
        // Regex pattern did not match
    }
} else {
    // Invalid regex pattern retrieved from the database
}