why won't this string validation script work?
These functions are in a class file and they are being passed variables through a form. Why will it say No match if I pass it a string with just the characters a-z or A-Z?
function pattern_check($patten, $string) {
$pass = preg_match($patten, $string);
return $pass;
}
function check_name($name) {
$pat = '/^[a-zA-Z]/';
$name = $this->pattern_check($pat, $name);
if($name) {
echo "Match"开发者_如何学运维;
}
else {
echo 'No match';
}
}
The only thing you are currently trying to validate is, that the first char in your string is a letter. Nothing more, nothing less.
If you want to check the complete string for only being letters you will have to use a regex like '#^[a-zA-Z]+$#'
. This ensures, that there are more than one letter is allowed. Also you will have to watch out with the encoding the tested string is of. If the string is utf8 you will have to use the u
modifier with your regex like #^[a-zA-Z]+#u
This seems to work exactly as you have specified. It checks that a string starts with an alphabetic character. Your string must not be what you think it is.
I wrapped this in a test function and fed it some strings:
function test($name)
{
echo "${name}: ";
check_name($name);
echo "\n";
}
test(" ZZ1");
test("123");
test("4aa");
test("AAA");
test("Z11");
test("ZZ ");
test("ZZZ");
test("aaa");
test("zzz");
test("Ábc");
Output...
% ./test.php
ZZ1: No match
123: No match
4aa: No match
AAA: Match
Z11: Match
ZZ : Match
ZZZ: Match
aaa: Match
zzz: Match
Ábc: No match
% php --version
PHP 5.3.4 (cli) (built: Dec 15 2010 12:15:07)
Copyright (c) 1997-2010 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2010 Zend Technologies
The reuse of your $name
variable may be confusing:
$name = $this->pattern_check($pat, $name);
if($name) {
Consider using this instead:
$matched = $this->pattern_check($pat, $name);
if ($matched) {
If these functions are not a part of a php class .. then the error is in your line
$name = $this->pattern_check($pat, $name);
change it to
$name = pattern_check($pat, $name);
Let me know if it works?
UPDATE -- Sorry then .. as I just tested it quickly and it seemed to work
class mytest{
private function pattern_check($patten, $string) {
$pass = preg_match($patten, $string);
return $pass;
}
public function check_name($name) {
$pat = '/^[a-zA-Z]/';
$name = $this->pattern_check($pat, $name);
if($name) {
echo "Match";
}
else {
echo 'No match';
}
}
}
$obj = new mytest();
$obj->check_name('ABCDEFG');
OUTPUT -> Match
I have realized that the regular expression is incorrect, the correct pattern to check for a proper name would be to make sure it's capitalized with lowercase letters after said capital so,
[A-Z]*[a-z]{1,50} would match true against any word starting with a capital and followed immediately after the capital with lowercase letters between 1 and 50 characters.
精彩评论