验证此字符串格式的最佳/最快方法是什么;A000AA00“;在PHP中?

验证此字符串格式的最佳/最快方法是什么;A000AA00“;在PHP中?,php,regex,Php,Regex,我需要验证我的字符串$path是否正好包含8个字符,并且$path是否符合以下模式:A000AA00其中A是任意字母A-Z,0是任意数字0-9 我做的第一件事是使用strlen获取字符串长度 if (strlen($path) !== 8) { die('Bad string length'); } 接下来,我使用ctype\u alpha和ctype\u digit检查字符串是否符合我期望的格式$path[0-7] if (ctype_alpha($path[0]) && c

我需要验证我的字符串
$path
是否正好包含8个字符,并且
$path
是否符合以下模式:
A000AA00
其中A是任意字母A-Z,0是任意数字0-9

我做的第一件事是使用
strlen
获取字符串长度

if (strlen($path) !== 8) { die('Bad string length'); }
接下来,我使用
ctype\u alpha
ctype\u digit
检查字符串是否符合我期望的格式
$path[0-7]

if (ctype_alpha($path[0]) && ctype_digit($path[1]) && ctype_digit($path[2]) && ctype_digit($path[3]) && ctype_alpha($path[4]) && ctype_alpha($path[5]) && ctype_digit($path[6]) && ctype_digit($path[7])) { // We good }

我能改进一下这个代码吗?
有更快的替代方案吗?

如果您计划使用正则表达式验证这种模式,您可以尝试

preg_match('~^[A-Z]\d{3}[A-Z]{2}\d{2}\z~', $s)
regex方法可读性很强:以大写字母开始,3位数字,2位大写字母,2位数字,字符串结尾

现在,

$path=“A000AA00”;
$startA=微时间(真);
对于($i=0;$i<100000;$i++)
{
if(strlen($path)!==8){die('Bad string length');}
如果(ctype_alpha($path[0])&&ctype_digit($path[1])&&ctype_digit($path[2])&&ctype_digit($path[3])&&ctype_alpha($path[4])&&ctype_alpha($path[5])&&ctype_digit($path[6])&&ctype_digit($path[7]){//我们很好
}
}
$endA=微时间(真);
echo$endA-$startA;

0.02226710319519
(PHP7.3.2),以及基于正则表达式的解决方案
0.0064888000488281

如果您计划使用正则表达式验证这种模式,您可以尝试

preg_match('~^[A-Z]\d{3}[A-Z]{2}\d{2}\z~', $s)
regex方法可读性很强:以大写字母开始,3位数字,2位大写字母,2位数字,字符串结尾

现在,

$path=“A000AA00”;
$startA=微时间(真);
对于($i=0;$i<100000;$i++)
{
if(strlen($path)!==8){die('Bad string length');}
如果(ctype_alpha($path[0])&&ctype_digit($path[1])&&ctype_digit($path[2])&&ctype_digit($path[3])&&ctype_alpha($path[4])&&ctype_alpha($path[5])&&ctype_digit($path[6])&&ctype_digit($path[7]){//我们很好
}
}
$endA=微时间(真);
echo$endA-$startA;

0.02226710319519
(PHP7.3.2),以及基于正则表达式的解决方案
0.0064888000488281

Try
preg\u match('~^[A-Z]\d{3}[A-Z]{2}\d{2}\Z~,$s)
@WiktorStribi\380ew。preg_-match是一个更快的替代方案吗?根据现有代码对preg_-match进行基准测试并不重要,但我敢打赌,您会发现结果无关紧要。如果(ctype_alpha($path[0]。$path[4]。$path[5])&&ctype_digit($path[1]。$path[2]。$path[3]。$path[6]。$path[7]){//We good}尝试
preg_match('~^[a-Z].$d{3}[a-Z]{2}\d{2}\Z~,$s)
@wiktoribi}我会尝试一下,并比较差异。preg_-match是一个更快的替代方案吗?根据现有代码对preg_-match进行基准测试并不重要,但我敢打赌,您会发现结果无关紧要。不要针对您甚至不确定是否存在的问题进行预优化。如果(ctype_alpha($path[0]。$path[4]。$path[5])&&ctype_digit($path[1]。$path[2]。$path[3]。$path[6]。$path[7]){//我们很好}