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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

help with preg_match

Status
Not open for further replies.

mufka

ISP
Dec 18, 2000
587
US
I'm using the following to validate a form field

Code:
!preg_match("/^[-a-z\,\.\:\'\s]+$/i",$_POST["subject"])

I cannot see why the form fails to validate if there is an ' in the submission.
 
are you trying to say that the field must only contain a comma, dash, full stop, single quote, colon and alphabet (and space)

if so, i'm not sure why your escaping so much stuff. i'd only look to escape the dash. i think that's probably the issue.

Code:
$pattern = "/^[a-z \-,.:']+$/i";

you should also test for 0 rather than false (to be precise). preg_match returns an integer corresponding to the number of matches.

Code:
if ( preg_match($pattern, $subject) === 0 ){
 echo 'invalid form field';
}

 
Code:
$pattern = "/^[a-z \-,.:']+$/i";
doesn't work either. It still won't allow an ' in the field.
 
i can't help you then. on my machines this code

Code:
<?php
$pattern = "/^[a-z \-,.:']+$/i";
$subject[] = "I am a test string";
$subject[] = "I am a John O'Connor";
$subject[] = "I am a test with illegal [characters]";
foreach($subject as $s){
	if(preg_match($pattern, $s) === 0 ){
		echo "string not matched";
	} else {
		echo "string matched";
	}
	echo "<br/>";
}
?>

results in this
Code:
string matched
string matched
string not matched

which is as expected.
 
Using $subject instead of $_POST["subject"] fixed it. I also changed to testing for 0 while I was at it.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top