除非您对该技术进行数十万次迭代,否则我认为“速度”不应作为决策标准考虑在内。
对我来说,我非常重视直接性然后是可读性。出于这个原因,我可能不会接受一种生成数组、合并循环或坦率地说进行多个函数调用的技术。正则表达式并不邪恶(我喜欢它),所以除非有另一种单功能技术,否则我每次都选择正则表达式。
也就是说,我发现的唯一非正则表达式方式(不是非常复杂)是@rid 用strcspn() 评论的。
-
preg_match() 的好处是更简洁,可以说更容易阅读,并且如果您的项目将来需要支持多字节字符,也不会让人头疼。
-
strcspn() 不会生成必须从中提取正确值的临时数组/变量,并且很可能优于任何 preg_ 调用,但没有明显/有价值的程度。
请注意,在我的演示中,“字符掩码”似乎接受的字符范围不超过一个。如果我可以指定 A..Za..z0..9 会很方便,但我无法让它工作。
代码:(Demo)
$strings = [
')(8234@#$ABCFG3478&* hello', // mix
'456456', // numeric
'ghijkl', // alphabetic
'!@#$%^&*(', // non-alphanumeric
];
foreach ($strings as $string) {
var_export(
[
'string' => $string,
'firstAlphaNumeric1' => preg_match('/[a-z0-9]/i', $string, $match) ? $match[0] : null,
'firstAlphaNumeric2' => $string[strcspn($string, 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789')] ?? null,
'firstAlphaNumeric3' => $string[strcspn($string, 'A..Zabcdefghijklmnopqrstuvwxyz0123456789')] ?? null,
]
);
echo "\n";
}
输出:
array (
'string' => ')(8234@#$ABCFG3478&* hello',
'firstAlphaNumeric1' => '8',
'firstAlphaNumeric2' => '8',
'firstAlphaNumeric3' => '8',
)
array (
'string' => '456456',
'firstAlphaNumeric1' => '4',
'firstAlphaNumeric2' => '4',
'firstAlphaNumeric3' => '4',
)
array (
'string' => 'ghijkl',
'firstAlphaNumeric1' => 'g',
'firstAlphaNumeric2' => 'g',
'firstAlphaNumeric3' => 'g',
)
array (
'string' => '!@#$%^&*(',
'firstAlphaNumeric1' => NULL,
'firstAlphaNumeric2' => NULL,
'firstAlphaNumeric3' => NULL,
)
最终,我会选择preg_match(),因为在我作为 php 开发人员的职业生涯中,我已经使用了数千次。相反,我可能在我的职业生涯中最多使用过 1 次 strcspn()(除了在 Stack Overflow 上玩耍之外)——因此缺乏熟悉度/直观性。