簡體   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