tags:

views:

42

answers:

3

Hi,

Out of experience which is better to use

filter_input(INPUT_GET, ‘my_string’, FILTER_SANITIZE_STRING);

Or a regular expression preg_match for sanitizing user in-putted data ?

+2  A: 

I prefer filter_input over regex for this - as it is easier to read.

Richard Harrison
Yes plus trying to work out a good Regx sometimes can be a pain.
Oliver Bayes-Shelton
+2  A: 

It depends on what you want to do and which PHP version you're using. *filter_input* is a convenient method to validate some input data for a well known target format such as URLs, IP-addresses or eMail-addresses, but might only be available for PHP >= 5.2.

In order to validate custom data (e.g. comma-separated values string), a regular expression would be more appropriate and therefore the way to go.

Javaguru
Oh I see I wasn't sure what types of data it would work with. Good answer than thanks for that.
Oliver Bayes-Shelton
The OP talks about sanitation, yet you refer to validation... Granted, `preg_match` would be used for validation, yet both the title and `FILTER_SANITIZE_STRING` refer to sanitation.
Artefacto
I agree. But validation is the first step of sanitization, i.e. detect whether a string contains invalid data. If you wish to do sanitization another step is required, which consists of replacing the invalid input with some valid one. In case of a syntactically incorrect eMail-address (e.g. the user entered abc@gugu:com, which is obviously wrong) sanitizing the input will not lead automatically to the correct eMail-address, even tought the sanitized string might be syntactically correct. So it would make more sense to ask the user what to do with the invalid address instead of sanitizing it.
Javaguru
+1  A: 

The do different things. FILTER_SANITIZE_STRING only strips tags and optionally does a number of things.

preg_match matches an arbitrary regular expression. You probably meant preg_replace, which by the way you can use the filter extension through FILTER_CALLBACK.

Artefacto