Warning: session_start() [function.session-start]: open(/tmp/sess_7kqdhr7147cl15dipcfl4v7bc6, O_RDWR) failed: Disk quota exceeded (122) in /home/vipozico/forum.tutorials7.com/qa-include/qa-app-users.php on line 143
Valid Usernames - String Task
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
...