PHP preg_match 仅用于数字和字母,无特殊字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5553294/
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
PHP preg_match for only numbers and letters, no special characters
提问by user517593
I don't want preg_match_all ... because the form field only allows for numbers and letters... just wondering what the right syntax is...
我不想要 preg_match_all ......因为表单字段只允许数字和字母......只是想知道正确的语法是什么......
Nothing fancy ... just need to know the right syntax for a preg_match statement that looks for only numbers and letters. Something like
没什么特别的……只需要知道只查找数字和字母的 preg_match 语句的正确语法。就像是
preg_match('/^([^.]+)\.([^.]+)\.com$/', $unit)
But that doesn't look for numbers too....
但这也不是寻找数字......
回答by Jacob
If you just want to ensure a string contains only alphanumeric characters. A-Z, a-z, 0-9 you don't need to use regular expressions.
如果您只想确保字符串仅包含字母数字字符。AZ, az, 0-9 不需要使用正则表达式。
Use ctype_alnum()
Example from the documentation:
文档中的示例:
<?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";
}
}
?>
The above example will output:
上面的例子将输出:
The string AbCd1zyZ9 consists of all letters or digits.
The string foo!#$bar does not consist of all letters or digits.
回答by Vish
if(preg_match("/[A-Za-z0-9]+/", $content) == TRUE){
} else {
}
回答by Richard Dickinson
If you want to match more than 1, then you'll need to, however, provide us with some code and we can help better.
如果您想匹配 1 个以上,那么您需要向我们提供一些代码,我们可以提供更好的帮助。
although, in the meantime:
虽然,与此同时:
preg_match("/([a-zA-Z0-9])/", $formContent, $result);
print_r($result);
:)
:)