Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP preg_match for only numbers and letters, no special characters

Tags:

php

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

like image 645
user517593 Avatar asked Apr 05 '11 14:04

user517593


3 Answers

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

} else {

}
like image 64
Vish Avatar answered Sep 16 '22 13:09

Vish


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.
like image 29
Jacob Avatar answered Sep 17 '22 13:09

Jacob


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);

:)

like image 39
Richard Dickinson Avatar answered Sep 18 '22 13:09

Richard Dickinson