12

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

user517593
  • 2,833
  • 4
  • 17
  • 14

3 Answers3

32

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.
Jacob
  • 8,278
  • 1
  • 23
  • 29
16
if(preg_match("/[A-Za-z0-9]+/", $content) == TRUE){

} else {

}
Matt
  • 74,352
  • 26
  • 153
  • 180
Vish
  • 4,508
  • 10
  • 42
  • 74
  • 4
    It won't let me edit it because it's not enough characters, but ("/(A-Za-z0-9]+/", $content) should be ("/[A-Za-z0-9]+/", $content). Notice the [ instead of ( – emilyk Apr 03 '13 at 17:54
  • 1
    @emilyk tried two times to process an edit to fix this but got denied every time. So we'll stick with the not working version then. – bicycle Jun 10 '13 at 08:54
5

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

:)

KingCrunch
  • 128,817
  • 21
  • 151
  • 173
Richard Dickinson
  • 288
  • 1
  • 3
  • 10