What are the potential pitfalls of not properly defining allowed characters in PHP registration scripts?

If allowed characters are not properly defined in PHP registration scripts, it can lead to security vulnerabilities such as SQL injection or cross-site scripting attacks. To solve this issue, it is important to restrict user input to only allow certain characters that are necessary for registration fields.

// Define allowed characters for registration fields
$allowed_characters = "/^[a-zA-Z0-9_\-]+$/";

// Validate user input against allowed characters
if (!preg_match($allowed_characters, $username)) {
    // Invalid username format
    echo "Invalid username format. Please use only letters, numbers, underscores, and hyphens.";
}