简体   繁体   English

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

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

I want to make php fgets(STDIN). 我想制作php fgets(STDIN)。 But I don't know how to restrict the input count and i don't know how to accept only specific letters. 但是我不知道如何限制输入数量,也不知道只接受特定的字母。 Please guide me. 请指导我。 I write down the problems of mine. 我写下我的问题。 I'm the beginner in STDIN usage. 我是STDIN使用的初学者。 It's important for me because i have to do it in my Programming Test Exam. 这对我很重要,因为我必须在编程测试考试中进行。 Help me please. 请帮帮我。

Here is Problem 1 这是问题1

Problem 1: I want to get only 10 Letters from cmd input and these input should be W & S. 问题1:我只想从cmd输入中获取10个字母,这些输入应为W&S。

Here is Problem 2 这是问题2

Problem 2 : I want to get only 3 numbers and how to restrict the cmd input to only number. 问题2:我只想获取3个数字,以及如何将cmd输入限制为仅数字。

I just realized Ive misread your question for part 2, but this will work for part one and be a good help to start problem 2: 我刚刚意识到我已经读错了第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