简体   繁体   English

检查字符串是否包含数字和字母

[英]Check if a string contains numbers and letters

I want to detect if a string contains both numbers and letters.我想检测一个字符串是否同时包含数字和字母。

For example:例如:

  • Given PncC1KECj4pPVW , it would be written to a text file because it contains both.给定PncC1KECj4pPVW ,它将被写入一个文本文件,因为它包含两者。
  • Given qdEQ , it would not, because it only contains letters.鉴于qdEQ ,它不会,因为它只包含字母。

Is there a method to do this?有没有办法做到这一点?

I was trying to use我正在尝试使用

$string = PREG_REPLACE("/[^0-9a-zA-Z]/i", '', $buffer);

But it didn't work.但它没有用。

Any help would be appreciated.任何帮助,将不胜感激。

It seems the simplest way is just to do it in two regex's. 似乎最简单的方法就是在两个正则表达式中做到这一点。

if (preg_match('/[A-Za-z]/', $myString) && preg_match('/[0-9]/', $myString))
{
    echo 'Contains at least one letter and one number';
}

I suppose another way to do it is this below. 我想另一种方法是在下面这样做。 It says "a letter and then later on at some point a number (or vice versa)". 它写着“一封信,然后在某个时刻点上一个数字(反之亦然)”。 But the one above is easier to read IMO. 但上面的那个更容易阅读IMO。

if (preg_match('/[A-Za-z].*[0-9]|[0-9].*[A-Za-z]/', $myString))
{
    echo 'Contains at least one letter and one number';
}
if (preg_match('/[A-Za-z].*[0-9]|[0-9].*[A-Za-z]/', $myString))
{
    echo 'Secure enough';
}

Answer updated based on https://stackoverflow.com/a/9336130/315550 , thnx to https://stackoverflow.com/users/116286/jb 答案根据https://stackoverflow.com/a/9336130/315550更新,thnx到https://stackoverflow.com/users/116286/jb

This works cleanly: 这很干净:

$myString="abc123";
if( preg_match('([a-zA-Z].*[0-9]|[0-9].*[a-zA-Z])', $myString) ) 
{ 
    echo('Has numbers and letters.');
} else {
    echo("no");
}

To see it in action, copy it and paste it here: http://phptester.net/index.php?lang=en 要查看它的实际效果,请将其复制并粘贴到此处: http//phptester.net/index.php?lang = en

My only question is whether is had to be one regexp. 我唯一的问题是,是否必须是一个正则表达式。 I'd go with two or three (because you have to build a little complex regexp to do it at once. 我会选择两到三个(因为你必须建立一个复杂的正则表达式才能立刻完成它。

Let's say that you require to have: 假设您需要:

  • at least one upper case character [AZ] 至少一个大写字符[AZ]
  • at least one lower case character [az] 至少一个小写字符[az]
  • at least one number \\d 至少一个数字\\d
  • have password at least 7 characters long 密码至少7个字符

The easiest and the most effective solution: 最简单,最有效的解决方案:

if( preg_match( '~[A-Z]~', $password) &&
    preg_match( '~[a-z]~', $password) &&
    preg_match( '~\d~', $password) &&
    (strlen( $password) > 6)){
    echo "Good password";
} else {
    echo "Not so much";
}

Otherwise, in one regexp you will have to consider several options: 否则,在一个正则表达式中,您将不得不考虑几个选项:

  • [az][AZ]+\\d
  • [az]\\d+[AZ]
  • [AZ][az]+\\d
  • [AZ]\\d+[az]
  • \\d[az]+[AZ]
  • \\d[AZ]+[az]

Join it into one big and hardly readable "ored" regexp like: 加入一个大而难以读取的“ored”正则表达式:

~([a-z][A-Z]+\d|[a-z]\d+[A-Z]|[A-Z][a-z]+\d|[A-Z]\d+[a-z]|\d[a-z]+[A-Z]|\d[A-Z]+[a-z])~

Of course you can go with (when needing just check upper and lower case): 当然你可以去(当需要检查大小写时):

preg_match( '~([a-z][A-Z]|[a-z][A-Z])~');

And still have to check length manually. 并且仍然需要手动检查长度。 The second solution seems pretty ineffective and hard to read to me. 第二个解决方案似乎非常无效,很难读给我看。 My recommendation: go with the first one. 我的建议:跟第一个一起去。

PHP has a built-in function for this. PHP有一个内置函数。 It's called ctype_alnum . 它叫做ctype_alnum

if(!ctype_alnum($string)) {
  return $error;
}
// Continue on your way...

for checking if string contains numbers or not !! 用于检查字符串是否包含数字!!

function ContainsNumbers($String){
    return preg_match('/\\d/', $String) > 0;
}

If you need to support multiple languages, from PHP 5.1 additional escape sequences were added for the character types listed here . 如果您需要支持多种语言,则从PHP 5.1中为此处列出的字符类型添加了其他转义序列。

The following functions take advantage of this and allow you to check for letters and numbers in multiple alphabets: 以下功能利用了这一功能,允许您检查多个字母表中的字母和数字:

check any letter exists in string: 检查字符串中是否存在任何字母

function has_letter($x){
    if (preg_match("/[\p{L}]/u",$x)) {
            return true;
    }
    return false;
}

check string contains any number check字符串包含任何数字

function has_number($x) {
    if (preg_match("/[\p{N}]/u",$x)) {
        return true;
    }
    return false; 
}

Usage 用法

$string = '123اختبا';
has_letter($string); // true


$string = '೪౨౨'; 
has_number($string); // true

Both together as requested 两者一起按要求

$string='I am 28';
if (has_letter($string)&&has_number($string)){
    // true
}

$string='I am ౨೩೫';
if (has_letter($string)&&has_number($string)){
    // true
}

$string='Привет, друг, как ты?';
has_number($string); // false - this Russian text doesn't contain a number

Some of these answers are whack... I'm fan of shortest, cleanest solution.其中一些答案很糟糕……我喜欢最短、最干净的解决方案。 This is my basic library that I updated and improved over 20 years while making games.这是我在制作游戏时更新和改进了 20 多年的基本库。 Yes PHP has some built in functions to check some of this stuff, but I like simple, short word functions.是的 PHP 有一些内置函数来检查这些东西,但我喜欢简单、简短的单词函数。

Here are 2 examples, both do the exact same thing using my functions这里有两个例子,都使用我的函数做完全相同的事情

$fullname = abcSpc($_POST['fullname']) ? $_POST['fullname'] : false;
// Same As
if(abcSpc($_POST['fullname']){ $fullname=$_POST['fullname']; } else { $fullname=false; }

My Library我的图书馆

// BASIC FUNCTIONS, JAYY's LIBRARY
function abc ($input){ return preg_match('/^[A-Z]+$/i', $input); }
function abcSpc ($input){ return preg_match('/^[a-z][a-z\ ]*$/i', $input); }
function abcNum ($input){ return preg_match('/^[A-Z0-9]+$/i', $input); }
function abcNumSpc ($input){ return preg_match('/^[A-Z0-9\ ]+$/i', $input); }
function abcNumU ($input){ return preg_match('/^[A-Z0-9_-]+$/i', $input); }
function abcNumD ($input){ return preg_match('/^[A-Z0-9-]+$/i', $input); }
function num ($input){ if(strlen($input) > 24){ $input=0; }if(!preg_match('/^[0-9]+$/', $input)){ $input=0; } return $input; }
function numU ($input){ return preg_match('/^[0-9_-]+$/i', $input); }
function is_odd($num){ return($num & 1); }
function email ($input){ return filter_var($input, FILTER_VALIDATE_EMAIL); }
function is_url($input){ return preg_match('/^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}'.'((:[0-9]{1,5})?\/.*)?$/i',$input); }
function is_uri ($input){ return preg_match('/^[a-z0-9-]+$/i', $input); }

U = Underline, D = Dash... U = 下划线,D = 破折号...

NOTE: num() checks for length of string due to a player 5-10 years ago discovering that if you type in a very large number, it actually breaks the num() and produces a string that isn't just numbers.注意:num() 会检查字符串的长度,因为 5-10 年前的一位玩家发现,如果您输入非常大的数字,它实际上会破坏 num() 并生成一个不仅仅是数字的字符串。 You can either remove it or learn from my experience.您可以删除它或从我的经验中学习。 That player ended up getting millions of free war units which destroyed the round for that game.该玩家最终获得了数百万个免费战争单位,这些单位摧毁了该游戏的回合。 Was not fun figuring out what he did.弄清楚他做了什么并不好玩。

I hope this helps someone.我希望这可以帮助别人。 This is my first post, I don't normally get involved.这是我的第一篇文章,我通常不会参与其中。 I just like reading and learning from other peoples mistakes.我只是喜欢阅读和从别人的错误中学习。 Feel free to improve my library for me if you guys see room for improvements.如果你们看到改进的空间,请随时为我改进我的库。

Here you go. The following func checks and returns TRUE if string contains alphabetic characters (not only from Latin alphabet, Cyrillic, Greek, Hebrew and others are supported too) AND if it contain numeric characters (digits).给你 go。如果字符串包含字母字符(不仅来自拉丁字母,还支持西里尔字母、希腊字母、希伯来字母等)并且包含数字字符(数字),则以下函数检查并返回 TRUE。 Both digits and non-digit (but alphabetic) characters required for the function to return TRUE. function 返回 TRUE 所需的数字和非数字(但字母)字符。

function is_good_string($s) {
    return preg_match('/\w/u', $s, $dummy) && // any alphabetic unicode character
           preg_match('/\d/', $s, $dummy) && // AND digit
           preg_match('/\D/', $s, $dummy); // AND non-digit
}

If you want to match only alphanumeric chars (that is, consider the string as invalid as soon as there is anything else into it, like spaces or special characters), this should work. 如果你想匹配数字字母的字符(即,只要有别的进去,如空格或特殊字符考虑字符串为无效),这应该工作。

Otherwise, just remove the first preg_match() . 否则,只需删除第一个preg_match()

function myTest($string)
{
  echo "test '".$string."': "
    . intval(preg_match('/^[a-z\d]+$/i', $string) // has only chars & digits
        && preg_match('/[a-z]/i', $string)        // has at least one char
        && preg_match('/\d/', $string))          // has at least one digit
    . "\n";
}

myTest('aAa'); // => 0
myTest('111'); // => 0
myTest('aAa111bbb'); // => 1
myTest('111aAabbb'); // => 1
myTest('aAabbb111'); // => 1
myTest('111bBb222'); // => 1
myTest('111 bBb 222'); // => 0
myTest('$$$$'); // => 0

Hey here are some guidelines below: 嘿,这里有一些指导方针如下:

Issue: No validation on the digit inside the string For eg 问题:对字符串内的数字没有验证例如

 OM  4  OM,   OM4OM   ,  space  OM 4  OM  space,  space  OM4OM space. -----> No valdation over this??

Solution: 解:

if (preg_match("/[A-Za-z].*[0-9]/",$_POST["name"]))
    {
     header("location:http://localhost/Test1.html");
     exit;
    }
Logic:  /[A-Za-z].*[0-9]/

It says first characters and then at some point numbers. 它表示第一个字符,然后是某些点数字。

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

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