Page 1 of 1

Need help with preg_match against simple string

Posted: Thu Sep 30, 2010 10:12 pm
by erika
preg_match is the bane of my existence, I just don't get it. :banghead: I am using mod_rewrite to create SEO-friendly URLs and would like to minimize the security hole presented with $_GET by checking to ensure that contents include only alphanumeric characters, spaces, hyphens, and underscores.

I am passing restaurant types which include, for example:

Pizza
Other - Dining
Cajun/Creole

On the linking page I am re-writing the above to:

Pizza
Other%20-%20Dining
Cajun_Creole

The data I get is exactly what I sent, except for the %20s, which turn back into spaces.

So I thought I could do something like this:

Code: Select all

	$category = $_GET['category'];

	$good_chars = '/[a-zA-Z0-9]/';

	if (preg_match($good_chars,$category)) {

		print $category . " has bad characters in it.";
	}

	else {

		print $category . " has no bad characters.";
	}
But that results in 100% rejection of the strings.

I thought maybe I had it backwards, so I put a ! in front of preg_match, but that resulted in 100% acceptance of the strings.

I'm obviously missing something and I don't know what... knowing WHY would be even more helpful.

Any assistance at all is greatly appreciated.

Re: Need help with preg_match against simple string

Posted: Fri Oct 01, 2010 2:17 am
by cpetercarter
You need to tell the regex engine that anything between the beginning of the string (^) and the end ($) should be an alphanumeric character ([a-zA-Z0-9]) and that there may be one or more of them (+).

Code: Select all

$good_chars = '/^[a-zA-Z0-9]+$/';

Re: Need help with preg_match against simple string

Posted: Mon Oct 04, 2010 5:02 am
by erika
Thank you, that's exactly what I needed! :)