Duncan Palmer
Duncan Palmer

Reputation: 2913

Check if a string contains numbers and letters

I want to detect if a string contains both numbers and letters.

For example:

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.

Upvotes: 40

Views: 138743

Answers (11)

Oleksii Kuznietsov
Oleksii Kuznietsov

Reputation: 719

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). Both digits and non-digit (but alphabetic) characters required for the function to return 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
}

Upvotes: 0

Jayy Monster
Jayy Monster

Reputation: 34

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. Yes PHP has some built in functions to check some of this stuff, but I like simple, short word functions.

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...

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. 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.

Upvotes: 0

Mohammad Naji
Mohammad Naji

Reputation: 5442

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

Upvotes: 39

Krii
Krii

Reputation: 907

PHP has a built-in function for this. It's called ctype_alnum.

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

Upvotes: 4

OM4
OM4

Reputation: 1

Hey here are some guidelines below:

Issue: No validation on the digit inside the string For e.g.

 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.

Upvotes: -2

David D
David D

Reputation: 1295

If you need to support multiple languages, from PHP 5.1 additional escape sequences were added for the character types listed here.

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

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

Upvotes: 0

Yashesh P
Yashesh P

Reputation: 29

for checking if string contains numbers or not !!

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

Upvotes: 0

Jonathan M
Jonathan M

Reputation: 17441

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

Upvotes: 8

Maxime Pacary
Maxime Pacary

Reputation: 23011

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().

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

Upvotes: 0

Vyktor
Vyktor

Reputation: 20997

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 [A-Z]
  • at least one lower case character [a-z]
  • at least one number \d
  • have password at least 7 characters long

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:

  • [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]

Join it into one big and hardly readable "ored" regexp like:

~([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.

Upvotes: 7

jb.
jb.

Reputation: 10341

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.

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

Upvotes: 59

Related Questions