Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

reg exp question

Status
Not open for further replies.

bpw89

Programmer
Dec 17, 2006
11
US
Hi,
I am trying to make sure that a string contains only letters, and no other characters.

I am using:

function checkletters($string) {
if (!preg_match($string, "^([a-z]|[A-Z])*$")) {
return true;
} else {
return false;
}
}

I am getting this error:

"Warning: preg_match() [function.preg-match]: Delimiter must not be alphanumeric or backslash in /path/to/file.php on line 47"

Line 47 is the one that contains "if (!preg_match($string, "^([a-z]|[A-Z])*$")) {", so I know there is something wrong with my reg exp.

Question: am I doing this the 'right way' or is there a string function that I should use instead?

THANKS
 
Code:
function checkletters($input){
 //function returns true if no non-letters present in $input
 $input = trim($input); //get rid of extraneous spaces
 $pattern = '/^[a-zA-Z]/';
 if ( false === preg_match($input, $pattern)) {
   //no matches found so ok
   return true;
  } else {
   return false; 
}
 
Thanks for your suggestion.

As a rule of thumb, I usually think of a solution right after I give up and post a question. In this case, I used:

function checkletters($string) {
$bad = eregi_replace("([a-zA-Z]+)","",$string);
if($bad == "") {
return false;
} else {
return true;
}
}

The reason for returning true if there is a problem and false if it is OK, is so I can use syntax like this in the main script:

if(checkletters($string)) {
$error="invalid input";
}
 
I would have thought that my code would be quite a bit faster (PCRE is natively faster than POSIX)

Code:
function checkletters($input){
  return (preg_match(trim($input).  '/^[a-zA-Z]/')) ? TRUE :FALSE;
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top