settingsAccountsettings
By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy
Menusettings

Q: Valid Usernames - String Task

+5 votes

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

asked in PHP category by user samfred5830

1 Answer

+5 votes

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;
        }
    }
}
answered by user sam
...