Danny Fox
Danny Fox

Reputation: 40709

How to check, if a php string contains only english letters and digits?

In JS I used this code:

if(string.match(/[^A-Za-z0-9]+/))

but I don't know, how to do it in PHP.

Upvotes: 64

Views: 108237

Answers (10)

Firas Abd Alrahman
Firas Abd Alrahman

Reputation: 187

The following code will take care about special characters and spaces

$string = 'hi, how are you ?';
if (!preg_match('/[^A-Za-z0-9 #$%^&*()+=\-\[\]\';,.\/{}|":<>?~\\\\]+/', $string)) // '/[^a-z\d]/i' should also work.
{
    echo 'english';
}else
{
    echo 'non-english';
}

Upvotes: -1

user3439891
user3439891

Reputation: 11

if(preg_match('/^[A-Za-z0-9]+$/i', $string)){ // '/^[A-Z-a-z\d]+$/i' should work also
// $string constains both string and integer
}

The carrot was in the wrong place so it would have search for everything but what is inside the square brackets. When the carrot is outside it searches for what is in the square brackets.

Upvotes: 1

Ramin Rabiee
Ramin Rabiee

Reputation: 21

if (preg_match('/^[\w\s?]+$/si', $string)) {
    // input text is just English or Numeric or space
}

Upvotes: 2

Saurabh
Saurabh

Reputation: 1

PHP can compare a string to a regular expression using preg_match(regex, string) like this:

if (!preg_match('/[^A-Za-z0-9]+/', $string)) {
    // $string contains only English letters and digits
}

Upvotes: 0

HalfWebDev
HalfWebDev

Reputation: 7638

Have a look at this shortcut

if(!preg_match('/[^\W_ ] /',$string)) {

}

the class [^\W_] matches any letter or digit but not underscore . And note the ! symbol . It will save you from scanning entire user input .

Upvotes: 7

shakee93
shakee93

Reputation: 5386

if you need to check if it is English or not. you could use below function. might help someone..

function is_english($str)
{
    if (strlen($str) != strlen(utf8_decode($str))) {
        return false;
    } else {
        return true;
    }
}

Upvotes: 13

Maxime Pacary
Maxime Pacary

Reputation: 23021

Use preg_match().

if (!preg_match('/[^A-Za-z0-9]/', $string)) // '/[^a-z\d]/i' should also work.
{
  // string contains only english letters & digits
}

Upvotes: 112

vineeth
vineeth

Reputation: 357

if(ctype_alnum($string)) {
    echo "String contains only letters and numbers.";
}
else {
    echo "String doesn't contain only letters and numbers.";
}

Upvotes: 34

Vitamin
Vitamin

Reputation: 1526

if(preg_match('/[^A-Za-z0-9]+/', $str)) {
    // ...
}

Upvotes: 5

evilone
evilone

Reputation: 22740

You can use preg_match() function for example.

if (preg_match('/[^A-Za-z0-9]+/', $str))
{
  // ok...
}

Upvotes: 11

Related Questions