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
939 views
in Technique[技术] by (71.8m points)

regex - PHP: fastest way to check for invalid characters (all but a-z, A-Z, 0-9, #, -, ., $)?

I have to check the buffer input to a PHP socket server as fast as possible. To do so, I need to know if the input message $buffer contains any other character(s) than the following: a-z, A-Z, 0-9, #, -, . and $

I'm currently using the following ereg function, but wonder if there are ways to optimize the speed. Should I maybe use a different function, or a different regex?

if (ereg("[A-Za-z0-9].#-$", $buffer) === false)
{
    echo "buffer only contains valid characters: a-z, A-Z, 0-9, #, -, ., $";
}
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Try this function:

function isValid($str) {
    return !preg_match('/[^A-Za-z0-9.#\-$]/', $str);
}

[^A-Za-z0-9.#-$] describes any character that is invalid. If preg_match finds a match (an invalid character), it will return 1 and 0 otherwise. Furthermore !1 is false and !0 is true. Thus isValid returns false if an invalid character is found and true otherwise.


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

...