PHP preg_match用于仅匹配数字和字母,不包括特殊字符。

12

我不想使用 preg_match_all ... 因为表单字段仅允许输入数字和字母 ... 只是想知道正确的语法是什么...

没有什么复杂的...只需要知道 preg_match 语句寻找只包含数字和字母的正确语法即可。例如:

preg_match('/^([^.]+)\.([^.]+)\.com$/', $unit)

但那也不能查找数字....


1
请您再具体说明一下您想要做什么。 - Clement Herreman
你能详细说明一下你在这里想要实现什么吗?可以给个例子吗?你是想匹配所有的字母数字还是只匹配第一个,或者其他什么? - whoughton
你为什么不想使用 preg_match_all - gen_Eric
3个回答

32

如果您只想确保一个字符串仅包含字母和数字字符,A-Z、a-z、0-9,则不需要使用正则表达式。

使用ctype_alnum()

示例来自文档:

<?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 string AbCd1zyZ9 consists of all letters or digits.
The string foo!#$bar does not consist of all letters or digits.

3
我不知道 ctype_alnum 是什么意思。+1 - gen_Eric

16
if(preg_match("/[A-Za-z0-9]+/", $content) == TRUE){

} else {

}

4
由于字符数量不够,它不允许我进行编辑,但应该将"/(A-Za-z0-9]+/"更改为"/[A-Za-z0-9]+/",请注意使用方括号而非圆括号。 - emilyk
1
@emilyk尝试了两次进行编辑以修复此问题,但每次都被拒绝。因此我们将继续使用不起作用的版本。 - bicycle

5

如果你想匹配多个条件,那么你需要提供一些代码,我们可以更好地帮助你。

不过,在此期间:

preg_match("/([a-zA-Z0-9])/", $formContent, $result);
print_r($result);

:)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接