1

in my program php, I want the user doesn't enter any caracters except the alphabets like that : "dgdh", "sgfdgdfg" but he doesn't enter the numbers or anything else like "7657" or "gfd(-" or "fd54" I tested this function but it doesn't cover all cases :

preg_match("#[^0-9]#",$_POST['chaine'])

how can I achieve that, thank you in advance

Alan Moore
  • 73,866
  • 12
  • 100
  • 156
user201892
  • 277
  • 2
  • 4
  • 11
  • * See also [Open source RegexBuddy alternatives](http://stackoverflow.com/questions/89718/is-there) and [Online regex testing](http://stackoverflow.com/questions/32282/regex-testing) for some helpful tools, or [RegExp.info](http://regular-expressions.info/) for a nicer tutorial. – mario Nov 17 '12 at 16:51

3 Answers3

0

Only match letters (no whitespace):

preg_match("#^[a-zA-Z]+$#",$_POST['chaine'])

Explanation:

^         # matches the start of the line
[a-zA-Z]  # matches any letter (upper or lowercase)
+         # means the previous pattern must match at least once
$         # matches the end of the line

With whitespace:

preg_match("#^[a-zA-Z ]+$#",$_POST['chaine'])
Chris Seymour
  • 83,387
  • 30
  • 160
  • 202
0

Two things. Firstly, you match non-digit characters. That is obviously not the same as letter characters. So you could simply use [a-zA-Z] or [a-z] and the case-insensitive modifier instead.

Secondly you only try to find one of those characters. You don't assert that the whole string is composed of these. So use this instead:

preg_match("#^[a-z]*$#i",$_POST['chaine'])
Martin Ender
  • 43,427
  • 11
  • 90
  • 130
0

The simplest can be

preg_match('/^[a-z]+$/i', $_POST['chaine'])

the i modifier is for case-insensitive. The + is so that at least one alphabet is entered. You can change it to * if you want to allow empty string. The anchor ^ and $ enforce that the whole string is nothing but the alphabets. (they represent the beginning of the string and the end of the string, respectively).


If you want to allow whitespace, you can use:

Whitespace only at the beginning or end of string:

preg_match('/^\s*[a-z]+\s*$/i', $_POST['chaine'])

Any where:

preg_match('/^[a-z][\sa-z]*$/i', $_POST['chaine'])    // at least one alphabet

Only the space character is allowed but not other whitespace:

preg_match('/^[a-z][ a-z]*$/i', $_POST['chaine'])
nonopolarity
  • 146,324
  • 131
  • 460
  • 740