Bird
0
0

You want to accept only alphabetic characters from user input in PHP. Which code snippet correctly sanitizes and validates this input?

hard📝 Application Q8 of 15
PHP - Superglobals and Web Context
You want to accept only alphabetic characters from user input in PHP. Which code snippet correctly sanitizes and validates this input?
A$input = $_POST['name']; $clean = trim($input); if (is_string($clean)) { echo 'Valid'; } else { echo 'Invalid'; }
B$input = $_POST['name']; $clean = filter_var($input, FILTER_SANITIZE_STRING); if (filter_var($clean, FILTER_VALIDATE_ALPHA)) { echo 'Valid'; } else { echo 'Invalid'; }
C$input = $_POST['name']; $clean = htmlspecialchars($input); if (preg_match('/\d/', $clean)) { echo 'Valid'; } else { echo 'Invalid'; }
D$input = $_POST['name']; $clean = preg_replace('/[^a-zA-Z]/', '', $input); if (ctype_alpha($clean)) { echo 'Valid'; } else { echo 'Invalid'; }
Step-by-Step Solution
Solution:
  1. Step 1: Check sanitization for alphabets only

    preg_replace removes all non-alphabetic characters, leaving only letters.
  2. Step 2: Validate with ctype_alpha

    ctype_alpha checks if string contains only letters, confirming valid input.
  3. Final Answer:

    Use preg_replace to remove non-letters and ctype_alpha to validate -> Option D
  4. Quick Check:

    Regex sanitize + ctype_alpha validate alphabets [OK]
Quick Trick: Use preg_replace and ctype_alpha for letters only [OK]
Common Mistakes:
  • Using non-existent FILTER_VALIDATE_ALPHA
  • Assuming is_string validates content
  • Using preg_match to check digits for validation

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes