【问题标题】:Compare username to regular expression with PHP使用 PHP 将用户名与正则表达式进行比较
【发布时间】:2016-05-08 07:52:11
【问题描述】:

我以前从未使用过正则表达式,并研究了如何只允许我的用户名字段alphanumeric characters, dashes, dots, and underscores。我有以下表达式,但它似乎不起作用。

$string = "Joe_Scotto";

if (!preg_match('[a-zA-Z0-9_-.]', $string)) {
    echo "Does not match Regex";
} else {
    echo "Matches";
}

如果语句遵循“准则”,我希望语句返回 true,如果用户名包含我指定的内容以外的内容,则返回 false。任何帮助都会很棒。谢谢!

【问题讨论】:

    标签: php regex


    【解决方案1】:

    试试这个

    $string = "Joe_Scotto";
    
    if (!preg_match('/^[A-Za-z0-9_.]+$/', $string)) {
        echo "Does not match Regex";
    } else {
        echo "Matches";
    }
    

    【讨论】:

    【解决方案2】:

    你只匹配一个字符。试试这个:

    $string = "Joe_Scotto";
    
    if (!preg_match('/^[a-zA-Z0-9_.-]+$/', $string)) {
        echo "Does not match Regex";
    } else {
        echo "Matches";
    }
    

    + 符号表示:匹配直接在 + 之前定义的 1 个或多个字符(* 相同,但匹配 0 个或多个字符)。 还需要分隔符“/”(或任何其他分隔符)。 在字符类中,最好将 - 符号放在末尾,否则可能会被误解为从 _. 的范围 并在开头添加^(这意味着:从输入的开头匹配)和$到末尾(这意味着:匹配到输入的末尾)。否则,字符串的一部分也会匹配。

    【讨论】:

    • Warning: preg_match(): Compilation failed: range out of order in character class at offset 12 in /Applications/MAMP/htdocs/projects/g/test.php on line 5
    • 例如,如果我将$string 设置为Joe^Scotto,它仍然会返回Matches。我正在努力使alphanumeric, -, _, .以外的任何字符都可以返回Does not match Regex
    • @JoeScotto:我在答案中添加了更正;字符 ^$ 必须添加到正则表达式
    • 顺便说一句:有一个不错的在线正则表达式测试器可以帮助设计正则表达式模式:regex101.com
    【解决方案3】:

    你应该使用类似http://www.phpliveregex.com/p/ern

    $string = 'John_Buss';
    
    if (preg_match('/[A-z0-9_\-.]+/', $string)) {
        return true;
    } else {
        return false;
    }
    

    确保在正则表达式的开头和结尾添加/ 分隔符

    确保在-之前使用\转义字符

    确保添加+字符量词

    【讨论】:

      猜你喜欢
      • 2020-02-29
      • 2012-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多