简体   繁体   English

如何使用 preg_match 只允许包含字母和数字字符的字符串?

[英]How to use preg_match to only allow strings containing alphabetic and numeric characters?

I need a regex to accept only strings that contain both alphabetic and numeric characters.我需要一个正则表达式来只接受包含字母和数字字符的字符串。 For example:例如:

ABCDEF: wrong 
123456: wrong
!##$%@.: wrong
ABCD123!@$: wrong
ABC12389IKEIIJ29: **correct**

How can I do it with PHP?我怎样才能用 PHP 做到这一点?

preg_match('/^[0-9A-Z]*([0-9][A-Z]|[A-Z][0-9])[0-9A-Z]*$/', $subject);

If you want to allow small and capital letters, add an i at the end of the pattern string.如果要允许小写和大写字母,请在模式字符串的末尾添加i

Explanation:解释:

[0-9][AZ] matches one digit followed by one capital letter [0-9][AZ]匹配一位数字后跟一个大写字母

[AZ][0-9] matches one capital letter followed by one digit [AZ][0-9]匹配一个大写字母后跟一位数字

([0-9][AZ]|[AZ][0-9]) matches one of these two sequences ([0-9][AZ]|[AZ][0-9])匹配这两个序列之一

[0-9A-Z]* matches 0-n digits and/or capital letters [0-9A-Z]*匹配 0-n 个数字和/或大写字母

The idea is: A string which contains both (and only), letters and numbers, has at least one subsequence where a letter follows a digit or a digit follows a letter.想法是:同时包含(且仅包含)字母和数字的字符串至少有一个子序列,其中字母后跟数字或数字后跟字母。 All the other characters (preceding and following) have to be digits or letters.所有其他字符(前后)必须是数字或字母。

I feel the most professional and comprehensible way of doing this is to declare two lookaheads which individually demand a certain range of characters, then match one or more characters that satisfy both sets of whitelisted characters -- of course, all of this logic needs to be nested inside of start of string and end of string anchors.我觉得最专业也最容易理解的做法是先声明两个分别需要一定范围字符的lookaheads,然后匹配一个或多个满足这两组白名单字符的字符——当然,所有这些逻辑都需要嵌套在字符串开头和字符串结尾锚点内。

I'll demonstrate with preg_grep() applied to an array of test strings, but you can use the same pattern with preg_match() on a single string.我将演示将preg_grep()应用于测试字符串数组,但您可以在单个字符串上使用与preg_match()相同的模式。

Code: ( Demo )代码:(演示

$tests = [
    'ABCDEF',
    '123456',
    '9Z',
    '!##$%@.',
    'ABCD123!@$',
    'ABC12389IKEIIJ29',
];

var_export(
    preg_grep(
        '~^(?=.*[A-Z])(?=.*\d)[A-Z\d]+$~',
        $tests
    )
);

Output: (array of qualifying strings)输出:(符合条件的字符串数组)

array (
  2 => '9Z',
  5 => 'ABC12389IKEIIJ29',
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM