Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
330 views
in Technique[技术] by (71.8m points)

validation - PHP generating invalid strings

There's a lot of implementations for generating random strings that start with a string of allowable characters to pick from. I want to do the reverse and provide an alphabet of characters to exclude (all others being allowed).

The purpose of this is to test rejecting invalid form input so it does not need to be cryptographically secure, just sufficiently random. I could enumerate bunch of invalid entries but risk missing something. Not looking to test everything in one go - each test run could generate a handful of invalid strings to assert, and over time cover more of the full gamut.

Something like below where $valid contains allowable characters to exclude. Not sure if there's a faster/easier way to do this.

function randomInvalidChar($valid = '') {
    do {
        $ord = mt_rand(0, 1112063);            // size of utf-8 character set
        $char = mb_chr($ord, 'UTF-8');
        $isValid = mb_strpos($valid, $char);
    } while ( $isValid !== false );

    return $char;
}

$random_string = randomInvalidChar('1234567890.+-*/^');

// => "?"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...