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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2896450/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 08:03:00  来源:igfitidea点击:

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

phpregex

提问by zahir hussain

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

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

回答by Sarfraz

You can filter it like:

您可以像这样过滤它:

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

As for some symbols, you should be morespecific

至于一些符号,你应该具体

回答by Serge S.

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

您可以$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
}

If you need more symbols you can add them before ]

如果你需要更多的符号,你可以在之前添加它们 ]

回答by Guilherme Nascimento

Don't need regex, you can use the Ctypefunctions:

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

In your case use ctype_alnum, example:

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

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

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

回答by Alix Axel

Both these regexes should do it:

这两个正则表达式都应该这样做:

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

Or:

或者:

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

回答by RHaguiuda

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

实现这一目标的最佳和最灵活的方法是使用正则表达式。但我不确定如何在 PHP 中做到这一点,但本文可以提供帮助。关联

回答by Aditya P Bhatt

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!

希望能帮助到你!