Jump to content

preg_replace sanitation


keepitcoder

Recommended Posts

I'm trying to sanitize some form inputs (from xss/sql injection, etc.).

 

I was wondering if someone can help me write 2 different preg_replace statements, as I'm really confused by it. I need one that will allow only numbers up to 5 characters, and one that will allow a-zA-Z0-9 and spaces up to 48 characters.

 

I found this online, would something like this work?

 

 

$q = preg_replace("/[^a-zA-Z0-9 ]+/", '', $q);
$p = preg_replace("/[^0-9]+/", '', $p);

 

Can you guys help me or point me to some great and easy tutorial?

 

Thanks

Link to comment
https://forums.phpfreaks.com/topic/211322-preg_replace-sanitation/
Share on other sites

$Search = array
(
'~^[0-9]{5}$~',
'~^[a-zA-Z0-9\s]{48}$~'
);

if(preg_match($Search, $Text))
{
//It's sanatized
}

 

Basically it says "If $Text is either exactly 5 numbers, or exactly 48 characters of letters, numbers or spaces, then it is sanatized"

 

Is that what you're after? And if you still want a tutorial, I'd suggest either http://www.regular-expressions.info/ or find one here

 

http://www.phpfreaks.com/

Did any of you even read the question?

 

I need one that will allow only numbers up to 5 characters

 

/^\d{0,5}$/D

 

\d matches any single digit (0 through 9) and {0,5} means to match from zero up to a maximum of 5 of those digits. Alternatively, you could use [0-9] in place of \d^ and $ and D in combination mean that the pattern will match a string, only if the pattern matches the entire string.

 

one that will allow a-zA-Z0-9 and spaces up to 48 characters

 

/^[a-zA-Z0-9 ]{0,48}$/D

 

Hopefully you can work out the above for yourself.

 

Some good places to look for help:

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.