user517593
user517593

Reputation: 2883

PHP preg_match for only numbers and letters, no special characters

I don't want preg_match_all ... because the form field only allows for numbers and letters... just wondering what the right syntax is...

Nothing fancy ... just need to know the right syntax for a preg_match statement that looks for only numbers and letters. Something like

preg_match('/^([^.]+)\.([^.]+)\.com$/', $unit)

But that doesn't look for numbers too....

Upvotes: 12

Views: 67604

Answers (4)

POPI
POPI

Reputation: 871

Test it :

preg_match('/\A[a-z0-9]+\z/i', $myInput);

Upvotes: 0

Vish
Vish

Reputation: 4492

if(preg_match("/[A-Za-z0-9]+/", $content) == TRUE){

} else {

}

Upvotes: 16

Jacob
Jacob

Reputation: 8334

If you just want to ensure a string contains only alphanumeric characters. A-Z, a-z, 0-9 you don't need to use regular expressions.

Use ctype_alnum()

Example from the documentation:

<?php
$strings = array('AbCd1zyZ9', 'foo!#$bar');
foreach ($strings as $testcase) {
    if (ctype_alnum($testcase)) {
        echo "The string $testcase consists of all letters or digits.\n";
    } else {
        echo "The string $testcase does not consist of all letters or digits.\n";
    }
}
?>

The above example will output:

The string AbCd1zyZ9 consists of all letters or digits.
The string foo!#$bar does not consist of all letters or digits.

Upvotes: 32

Richard Dickinson
Richard Dickinson

Reputation: 278

If you want to match more than 1, then you'll need to, however, provide us with some code and we can help better.

although, in the meantime:

preg_match("/([a-zA-Z0-9])/", $formContent, $result);
print_r($result);

:)

Upvotes: 5

Related Questions