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
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/

Link to comment
Share on other sites

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:

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.