【问题标题】:PHP preg_match for only numbers and letters, no special charactersPHP preg_match 仅用于数字和字母,没有特殊字符
【发布时间】:2011-04-05 14:14:32
【问题描述】:

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

没什么特别的......只需要知道 preg_match 语句的正确语法,它只查找数字和字母。像

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

但这也不是寻找数字....

【问题讨论】:

  • 请把你想做的更准确一点。
  • 您能否详细说明您在这里想要实现的目标?也许是一个例子。您是要匹配所有字母数字还是仅匹配第一个字母数字或其他内容?
  • 你为什么不想要preg_match_all

标签: php


【解决方案1】:

如果您只想确保字符串仅包含字母数字字符。 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.

【讨论】:

  • 我不知道ctype_alnum。 +1
【解决方案2】:
if(preg_match("/[A-Za-z0-9]+/", $content) == TRUE){

} else {

}

【讨论】:

  • 它不允许我编辑它,因为它没有足够的字符,但是 ("/(A-Za-z0-9]+/", $content) 应该是 ("/[A- Za-z0-9]+/", $content)。注意 [ 而不是 (
  • @emilyk 尝试了两次来处理编辑以解决此问题,但每次都被拒绝。所以我们会坚持使用不工作的版本。
【解决方案3】:

如果您想匹配超过 1 个,那么您需要向我们提供一些代码,我们可以提供更好的帮助。

虽然在此期间:

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

:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-16
    • 1970-01-01
    • 2011-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多