使用 PHP 在字符串中只允许 [az][AZ][0-9]
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2896450/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Allow only [a-z][A-Z][0-9] in string using PHP
提问by zahir hussain
How can I get a string that only contains a to z, A to Z, 0 to 9 and some symbols?
如何获得仅包含 a 到 z、A 到 Z、0 到 9 和一些符号的字符串?
回答by Sarfraz
You can filter it like:
您可以像这样过滤它:
$text = preg_replace("/[^a-zA-Z0-9]+/", "", $text);
As for some symbols, you should be morespecific
至于一些符号,你应该更具体
回答by Serge S.
You can test your string (let $str) using preg_match:
您可以$str使用preg_match以下方法测试您的字符串 (let ) :
if(preg_match("/^[a-zA-Z0-9]+$/", $str) == 1) {
// string only contain the a to z , A to Z, 0 to 9
}
If you need more symbols you can add them before ]
如果你需要更多的符号,你可以在之前添加它们 ]
回答by Guilherme Nascimento
Don't need regex, you can use the Ctypefunctions:
不需要正则表达式,您可以使用以下Ctype功能:
ctype_alnum: Check for alphanumeric character(s)ctype_alpha: Check for alphabetic character(s)ctype_cntrl: Check for control character(s)ctype_digit: Check for numeric character(s)ctype_graph: Check for any printable character(s) except spacectype_lower: Check for lowercase character(s)ctype_print: Check for printable character(s)ctype_punct: Check for any printable character which is not whitespace or an alphanumeric characterctype_space: Check for whitespace character(s)ctype_upper: Check for uppercase character(s)ctype_xdigit: Check for character(s) representing a hexadecimal digit
ctype_alnum: 检查字母数字字符ctype_alpha: 检查字母字符ctype_cntrl: 检查控制字符ctype_digit: 检查数字字符ctype_graph: 检查除空格外的任何可打印字符ctype_lower: 检查小写字符ctype_print: 检查可打印字符ctype_punct: 检查任何非空格或字母数字字符的可打印字符ctype_space: 检查空白字符ctype_upper: 检查大写字符ctype_xdigit: 检查代表十六进制数字的字符
In your case use ctype_alnum, example:
在您的情况下使用ctype_alnum,例如:
if (ctype_alnum($str)) {
//...
}
Example:
例子:
<?php
$strings = array('AbCd1zyZ9', 'foo!#$bar');
foreach ($strings as $testcase) {
if (ctype_alnum($testcase)) {
echo 'The string ', $testcase, ' consists of all letters or digits.';
} else {
echo 'The string ', $testcase, ' don\'t consists of all letters or digits.';
}
}
Online example: https://ideone.com/BYN2Gn
在线示例:https: //ideone.com/BYN2Gn
回答by Alix Axel
Both these regexes should do it:
这两个正则表达式都应该这样做:
$str = preg_replace('~[^a-z0-9]+~i', '', $str);
Or:
或者:
$str = preg_replace('~[^a-zA-Z0-9]+~', '', $str);
回答by RHaguiuda
回答by Aditya P Bhatt
A shortcut will be as below also:
快捷方式也如下所示:
if (preg_match('/^[\w\.]+$/', $str)) {
echo 'Str is valid and allowed';
} else
echo 'Str is invalid';
Here:
这里:
// string only contain the a to z , A to Z, 0 to 9 and _ (underscore)
\w - matches [a-zA-Z0-9_]+
Hope it helps!
希望能帮助到你!

