使用PHP仅允许字符串中的[az] [AZ] [0-9]

zah*_*in 10 php regex

如何获得仅包含a到z,A到Z,0到9以及一些符号的字符串?

Sar*_*raz 27

你可以过滤它:

$text = preg_replace("/[^a-zA-Z0-9]+/", "", $text);
Run Code Online (Sandbox Code Playgroud)

至于某些符号,您应该具体


Ser*_* S. 26

您可以$str使用preg_match以下方法测试字符串(let ):

if(preg_match("/^[a-zA-Z0-9]+$/", $str) == 1) {
    // string only contain the a to z , A to Z, 0 to 9
}
Run Code Online (Sandbox Code Playgroud)

如果您需要更多符号,可以先添加它们 ]

  • 等等,没有分隔符? (2认同)

Gui*_*nto 11

不需要正则表达式,可以使用以下Ctype功能:

在你的情况下使用ctype_alnum,例如:

if (ctype_alnum($str)) {
    //...
}
Run Code Online (Sandbox Code Playgroud)

例:

<?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.';

    }
}
Run Code Online (Sandbox Code Playgroud)

在线示例:https://ideone.com/BYN2Gn