PHP-正则表达式仅允许使用字母和数字 [英] PHP - regex to allow letters and numbers only
本文介绍了PHP-正则表达式仅允许使用字母和数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试过:
preg_match("/^[a-zA-Z0-9]", $value)
但是我猜我做错了.
推荐答案
1.使用PHP内置的 ctype_alnum
您无需为此使用正则表达式,PHP具有内置函数ctype_alnum
,它将为您执行此操作,并且执行速度更快:
1. Use PHP's inbuilt ctype_alnum
You dont need to use a regex for this, PHP has an inbuilt function ctype_alnum
which will do this for you, and execute faster:
<?php
$strings = array('AbCd1zyZ9', 'foo!#$bar');
foreach ($strings as $testcase) {
if (ctype_alnum($testcase)) {
echo "The string $testcase consists of all letters or digits.\n";
} else {
echo "The string $testcase does not consist of all letters or digits.\n";
}
}
?>
2.或者,使用正则表达式
如果您非常想使用正则表达式,则有几种选择.
2. Alternatively, use a regex
If you desperately want to use a regex, you have a few options.
首先:
preg_match('/^[\w]+$/', $string);
\w
包含多个字母数字(包括下划线),但包含所有
\d
.
\w
includes more than alphanumeric (it includes underscore), but includes all
of \d
.
或者:
/^[a-zA-Z\d]+$/
甚至只是:
/^[^\W_]+$/
这篇关于PHP-正则表达式仅允许使用字母和数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文