posted 03/7/2008 by Chris

While regular expressions are often used for input validation, I also find them very useful for cleaning malicious code in user input. For this I used the function preg_replace. The idea is that I only allow certain characters through...

 

$input_text = "ABCXYZ...abcxyz..@..0189";

 

//blocks anything that is not an uppercase letter of the alphabet

echo preg_replace('/[^A-Z]/', '', $input_text); // returns ABCXYZ

 

//blocks anything that is not a letter of the alphabet

echo preg_replace('/[^A-Za-z]/', '', $input_text); // returns ABCXYZabcxyz

 

//blocks anything that is not a letter of the alphabet or a number

echo preg_replace('/[^A-Za-z0-9]/', '', $input_text); // returns ABCXYZabcxyz0189

 

//blocks anything that is not a letter, number or a period (.)

echo preg_replace('/[^A-Za-z0-9.]/', '', $input_text); // returns ABCXYZ...abc....0189

 

//blocks anything that is not a letter, number, period or @ symbol

echo preg_replace('/[^A-Za-z0-9.@]/', '', $input_text); // returns ABCXYZ...abc..@..0189

 

That should be enough examples for you to get the idea. The one confusing part is when you want to include a hyphen (-) well you just put "\-" so it turns out to be...

 

preg_replace('/[^A-Za-z0-9.\-@]/', '', $input_text);

 

 

 

Share:
facebook myspace digg del.icio.us fark stumbleupon live spurl furl reddit yahoo

COMMENTS (displaying 0 comments)

POST (leave a comment)

Name:
Email:
Message:
Verify:
CAPTCHA Image