繁体   English   中英

如何限制字母数并仅接受PHP STDIN中的特定字母?

[英]How to limit the letter count and accept only specific letters in PHP STDIN?

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

这是问题1

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

这是问题2

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

我刚刚意识到我已经读错了第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";

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM