【问题标题】:How to limit the letter count and accept only specific letters in PHP STDIN?如何限制字母数量并仅接受 PHP STDIN 中的特定字母?
【发布时间】:2017-08-13 23:55:31
【问题描述】:

我想制作 php fgets(STDIN)。但我不知道如何限制输入计数,也不知道如何只接受特定的字母。请指导我。我写下我的问题。我是 STDIN 使用的初学者。这对我来说很重要,因为我必须在我的编程测试考试中这样做。请帮帮我。

这是问题 1

问题 1:我只想从 cmd 输入中获取 10 个字母,而这些 输入应该是 W & S。

这是问题2

问题 2:我只想获取 3 个数字以及如何限制 cmd 只输入数字。

【问题讨论】:

    标签: php command-line-interface stdin


    【解决方案1】:

    我刚刚意识到我误读了您在第 2 部分中的问题,但这适用于第 1 部分,并且对开始问题 2 很有帮助:

    <?php
        $errorMessage = false;
        $attempts = 1;
        $maxAttempts = 5;
    
        function validates($string)
        {
            global $errorMessage; //tell this function to use global errormessage
            if (strlen($string) > 10) {
                $errorMessage = 'Exceeded String Length. Please ensure no more than 10 characters are entered';
                return false;
            }
            preg_match('/\d+/', $string, $matches);
            $extractedDigits = (isset($matches[0]) ? $matches[0] : 0 );
            if ($extractedDigits > 3) {
                $errorMessage = 'Exceeded allowed number of digits. Please ensure no more than 3 digits are contained in the string';
                return false;
            }
            $errorMessage = false;
            return true;
        }
        $result = readline('please enter a valid string: ');
        while (!validates($result) && $attempts < $maxAttempts) { //while fail validation and have attempted less than the max attampts
            echo "\n";
            echo '*******************************************';
            echo "\n";
            echo 'Attempts  Left (' . ($maxAttempts - $attempts) . ')';
            echo "\n";
            $result = readline($errorMessage . '. Please try again: ');
            $attempts++;
        }
        echo "\n";
        echo '*******************************************';
        echo "\n";
        if ($attempts >= $maxAttempts) {
            echo 'Failed, too many attempts';
        } else {
            echo "\n";
            echo 'Success...';
            echo "\n";
            echo "\n";
            echo $result;
            echo "\n";
            echo "\n";
        }
        echo "\n";
    

    【讨论】:

    • 第二部分只需要调整验证功能
    猜你喜欢
    • 2014-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-12
    • 2012-09-29
    • 1970-01-01
    相关资源
    最近更新 更多