Bird
0
0

You want to accept a username that only contains letters, numbers, and underscores. Which PHP code correctly validates this input using filter_var() and a custom pattern?

hard📝 Application Q15 of 15
PHP - Superglobals and Web Context
You want to accept a username that only contains letters, numbers, and underscores. Which PHP code correctly validates this input using filter_var() and a custom pattern?
A$username = $_POST['username']; if (filter_var($username, FILTER_VALIDATE_REGEXP, ['options' => ['regexp' => '/^[a-zA-Z0-9_]+$/']])) { echo "Valid username"; } else { echo "Invalid username"; }
B$username = $_POST['username']; if (filter_var($username, FILTER_SANITIZE_STRING)) { echo "Valid username"; } else { echo "Invalid username"; }
C$username = $_POST['username']; if (filter_var($username, FILTER_VALIDATE_EMAIL)) { echo "Valid username"; } else { echo "Invalid username"; }
D$username = $_POST['username']; if (filter_var($username, FILTER_VALIDATE_INT)) { echo "Valid username"; } else { echo "Invalid username"; }
Step-by-Step Solution
Solution:
  1. Step 1: Understand the requirement

    The username must only have letters, numbers, and underscores, so a regular expression is needed to check this pattern.
  2. Step 2: Use FILTER_VALIDATE_REGEXP with correct pattern

    FILTER_VALIDATE_REGEXP allows validating input against a regex pattern. The pattern '/^[a-zA-Z0-9_]+$/' matches only allowed characters.
  3. Step 3: Eliminate distractors

    The incorrect options use filters for integer validation, string sanitization, or email validation, none of which enforce the specific pattern of letters, numbers, and underscores.
  4. Final Answer:

    Code using FILTER_VALIDATE_REGEXP with pattern '/^[a-zA-Z0-9_]+$/' -> Option A
  5. Quick Check:

    Validate username with FILTER_VALIDATE_REGEXP + regex [OK]
Quick Trick: Use FILTER_VALIDATE_REGEXP with regex for custom pattern validation [OK]
Common Mistakes:
  • Using sanitize instead of validate
  • Using email or int filters for username
  • Not using regex for pattern matching

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes