[Solved] Valid Usernames - String Task

  

4
Topic starter

Write a program that reads usernames on a single line (joined by ", ") and prints all valid usernames.

A valid username is:

  • Has length between 3 and 16 characters
  • Contains only letters, numbers, hyphens - and underscores _
  • Has no redundant symbols before, after or in between

Examples:

valid usernames string task

1 Answer
3

Interesting task 🙂 Here is my solution:

<?php
 
$usernames = explode(", ", readline());
 
foreach ($usernames as $username) {
    $length = strlen($username);
    if ($length >= 3 && $length <= 16) {
        $isValid = true;
        for ($i = 0; $i < $length; $i++) {
            $currChar = $username[$i];
            if (!(ctype_alnum($currChar) || $currChar === "_" || $currChar === "-")) {
                $isValid = false;
                break;
            }
        }
        if ($isValid) {
            echo $username . PHP_EOL;
        }
    }
}
Share: