hi, i don't know how write regexp (preg_match() in php) and i wanna following regexps:
1. just number
2. just words
3. just words, numbers, -._
tanks.
Printable View
hi, i don't know how write regexp (preg_match() in php) and i wanna following regexps:
1. just number
2. just words
3. just words, numbers, -._
tanks.
There are a few different ways to use those regular expressions but I laid out a simple preg_match function stored in each variable above.Code:$reg1 = preg_match("/[0-9]/", "String to check"); // Only numbers
$reg2 = preg_match("/[a-z]/i", "String to check"); // Only letters
$reg3 = preg_match("/[a-z0-9-._]/i", "String to check"); // numbers, letters and -._
Those checks are all well and good, if all you want to know if is the string contains "a letter" , "a number" or "a letter, number, hyphen, period, or underscore".
I'm going to assume this is for validating some type of login or password?
If that's the case, you probably want to check for things OTHER than what you want.
Take a look at these examples:
PHP Code:$test_string = "Str1ng-t0_ch3ck.";
$test_string_words = "Stringtocheck";
$test_string_numbers = "12345";
$test_string_mixed = "Str1ng t0 ch3ck."; // note the added spaces; need to add \s to the regex patterns to match this
$reg1 = preg_match("/[^0-9]/", $test_string); // Only numbers
$reg1a = preg_match("/[^0-9]/", $test_string_numbers); // Only numbers
$reg2 = preg_match("/[^a-z]/i", $test_string); // Only letters
$reg2a = preg_match("/[^a-z]/i", $test_string_words); // Only letters
$reg3 = preg_match("/[^a-z0-9-._]/i", $test_string); // numbers, letters and -._
$reg4 = preg_match("/[^\w-._]/i", $test_string_mixed); // numbers, letters and -._
/*
preg_match returns int(1) if it finds a match to the pattern or int(0) if it does not find a match.
since these checks are checking for NOT IN THE PATTERN, then (if $var === 0) "passes" the regex and (if $var === 1) "fails"
{three "equal signs" matches exactly the type int()}
------------ reg1 (it found something other than just numbers)
1
------------
------------ reg1a (it found only numbers)
0
------------
------------ reg2 (it found something other than just letters)
1
------------
------------ reg2a (it found only letters)
0
------------
------------ reg3 (it found only the acceptable characters)
0
------------
------------ reg4 (condensed "word boundries (letter and numbers) plus the `extra characters`")
1
------------
*/
Also, please see the various ctype_*() functions for more efficient ways to do certain checks.
i want check input and
1.if it was just numbers return 1 and if it has characters return 0.
2.if it was just characters return 1 and if it has numbers return 0.
3.if it was just characters and numbers return 1 and if it has else characters line &,*,... return 0.
3.if it was just characters and numbers and -_. return 1 and if it has else characters line &,*,... return 0.