Alex
Alex

Reputation: 68084

Using filter_var to sanitize a string

http://www.php.net/manual/en/filter.filters.flags.php

How can I use this function to strip down a string to just a-z, numbers and _ ?

Upvotes: 3

Views: 1887

Answers (2)

Savas Vedova
Savas Vedova

Reputation: 5692

Apparently you can't. Because what you ask is actually something between 65 to 90 and 97 to 122. The filter will strip the characters that have a numeric value less than 32 and greater than 127. You should go for regex instead.

Upvotes: 2

Nameless
Nameless

Reputation: 2366

You will have to use callback filter and write your function

function my_filter($value)
{
    return preg_replace('/[^a-z\d_]/iu', '', $value);
}
$var = filter_var($var, FILTER_CALLBACK, array('options' => 'my_filter'));

If you want only lowercase letters in your filtered var, remove 'i' flag from regex.

And of course, using filter_var is just being excess code here. This is shorter.

$var = preg_replace('/[^a-z\d_]/iu', '', $var);

Upvotes: 2

Related Questions