What are the best practices for handling special characters in usernames in PHP applications?

Special characters in usernames can potentially cause issues when handling data in PHP applications, such as SQL injection or cross-site scripting vulnerabilities. To mitigate these risks, it is recommended to sanitize and validate usernames by allowing only alphanumeric characters, underscores, and dashes. This can be achieved by using regular expressions to check for unwanted characters and rejecting usernames that do not meet the specified criteria.

// Sanitize and validate username
$username = $_POST['username'];

if (!preg_match('/^[a-zA-Z0-9_-]+$/', $username)) {
    // Invalid username format
    echo 'Invalid username format. Please use only alphanumeric characters, underscores, and dashes.';
} else {
    // Username is valid, proceed with processing
    // Your code here
}