Allow only [a-z][A-Z][0-9] in string using PHP

前端 未结 6 1502
栀梦
栀梦 2020-11-28 14:38

How can I get a string that only contains a to z, A to Z, 0 to 9 and some symbols?

相关标签:
6条回答
  • 2020-11-28 14:59

    You can filter it like:

    $text = preg_replace("/[^a-zA-Z0-9]+/", "", $text);
    

    As for some symbols, you should be more specific

    0 讨论(0)
  • 2020-11-28 14:59

    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!

    0 讨论(0)
  • 2020-11-28 14:59

    The best and most flexible way to accomplish that is using regular expressions. But I`m not sure how to do that in PHP but this article can help. link

    0 讨论(0)
  • 2020-11-28 15:15

    Don't need regex, you can use the Ctype functions:

    • 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 space
    • ctype_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 character
    • ctype_space: Check for whitespace character(s)
    • ctype_upper: Check for uppercase character(s)
    • ctype_xdigit: Check for character(s) representing a hexadecimal digit

    In your case use ctype_alnum, example:

    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

    0 讨论(0)
  • 2020-11-28 15:19

    Both these regexes should do it:

    $str = preg_replace('~[^a-z0-9]+~i', '', $str);
    

    Or:

    $str = preg_replace('~[^a-zA-Z0-9]+~', '', $str);
    
    0 讨论(0)
  • 2020-11-28 15:22

    You can test your string (let $str) using preg_match:

    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 ]

    0 讨论(0)
提交回复
热议问题