Dynadot โ€” .com Registration $8.99

Eregi or Preg_Match Regex problem

Spaceship Spaceship
Watch

LazyD

Established Member
Impact
0
Im trying to get a function to work to validate/sanitize $_GET vars on one of my sites but im having problems...

So, for instance a URL could look like - http://mysite.com/state.php?State=New+Hampshire.html or
http://mysite.com/state.php?State=California.html

The New+Hampshire or California is then put into a variable from $_GET

California works fine, im having no problems with that...

I want to use regex through eregi or even preg_match to check New+Hampshire for invalid characters, I only want a-zA-Z and + to be valid, anything else I want to fail validation, the problem is no matter how I try I can never get the + to validate...
 
0
•••
The views expressed on this page by users and staff are their own, not those of NamePros.
GoDaddyGoDaddy
Can you post the code that isn't working for you?

I can help you debug it.
 
0
•••
PHP:
function sanitizeVar($source) {
	if(preg_match('/^[a-zA-Z]+[+a-zA-Z]+[a-zA-Z]\z/i', $source)) {
		return $source;
	}
	else {
		die("One or more variables are invalid");
	}
}

Then to use it...
PHP:
$StateName = $_GET['State'];

if(isset($StateName)) {
sanitizeVar($StateName)
}

It works fine for States that are one word, anything else, it just does the die command...
 
0
•••
LazyD,

Your code actually works for me (how i think it should work), however this is a little better and may sort out any problems you are having:

PHP:
if(preg_match('/^[A-z+]+\z/i', $source)) {

Matt
 
0
•••
0
•••
Well I don't understand that...it works fine for me (your exact code).

Just humour me one moment and try this:
PHP:
<?php

$string = 'New+Hampshire';

function sanitizeVar($source) {
    if(preg_match('/^[A-z+]+\z/i', $source)) {
		echo 'Fine';
    }
    else {
        echo 'One or more variables are invalid';
    }
}  

sanitizeVar($string);

?>

(ignore the query string you want to use)
 
0
•••
That script works fine the way it is...

As soon as I change the sanitizeVar($string); to sanitizeVar($StateName); it spits out an error saying its invalid...
 
0
•••
Ah OK. Never thought about this.

Try outputting $_GET['State'] - Notice how the + symbol is not actually present anymore. Somewhere along the line (and if I'm honest I'm not sure where) + is being changed to a space, so we can either reverse that like so:

PHP:
$StateName = str_replace(' ', '+', $StateName);

Or we can just do this: (probably better, but we loose the + form the script)
PHP:
if(preg_match('/^[A-z+ ]+\z/i', $source)) {

Matt
 
1
•••
Neither did I... But it WORKS!

Thank you very much Matt... +Rep
 
0
•••
Not a problem, thanks for the rep :tu:

Matt
 
0
•••
Appraise.net
Unstoppable Domains
Domain Recover
NameMaxi - Your Domain Has Buyers
  • The sidebar remains visible by scrolling at a speed relative to the pageโ€™s height.
Back