PHP:检查无效字符(除了a-z,A-Z,0-9,#,-,.,$)以外的最快方法? [英] PHP: fastest way to check for invalid characters (all but a-z, A-Z, 0-9, #, -, ., $)?
问题描述
我必须尽可能快地检查输入到PHP套接字服务器的缓冲区.为此,我需要知道输入消息$ buffer是否包含除以下字符以外的任何其他字符: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 $
我当前正在使用以下ereg函数,但想知道是否存在优化速度的方法.我应该使用其他功能还是其他正则表达式?
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, #, -, ., $";
}
推荐答案
尝试使用此功能:
function isValid($str) {
return !preg_match('/[^A-Za-z0-9.#\\-$]/', $str);
}
[^A-Za-z0-9.#\-$]
描述任何无效字符.如果preg_match
找到匹配项(无效字符),则将返回 1 和 0 .此外,!1
是 false ,而!0
是 true .因此,如果找到无效字符,则isValid
返回 false ,否则返回 true .
[^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.
这篇关于PHP:检查无效字符(除了a-z,A-Z,0-9,#,-,.,$)以外的最快方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!