views:

32

answers:

1

How do I restrict a string to whitelisted characters?

// "HOW am I to understand; this is, BAD"

$str = restrictTo($str,"0-9a-z,. ");

// " am I to understand this is, "

Is there an inbuilt function in PHP that does something close? I can't formulate a regular expression for this though :(

+2  A: 

Ok, If you just want to replace characters, use preg_replace (Note, you can add any character with a few caviats.

  1. If you want to add -, it MUST be at the end of the list
  2. If you want to add a \, it MUST be escaped by another \
  3. If you want a /, [ or ], it must be escaped by a \)

This allows certain characters and filters out the rest:

$str = preg_replace('/[^A-Za-z,.]/', '', $str);

If you want to reject any string that has any character that doesn't match:

if (preg_match('/[^A-Za-z.,]/', $str)) {
    //Rejected String
}
ircmaxell
How do I filter out spaces? or allow spaces to remain in the string?
Jenko
If you only want literal spaces, you can add `\040` for the character class (after the `.`). If you want all white space characters (including new lines, tabs, etc) you can add `\s`. For more info: http://www.php.net/manual/en/regexp.reference.backslash.php
ircmaxell