Restrict characters used in a string
How do I restrict a string to whitelisted characters?
// "HOW am I to understand; this is, BAD"
$str = res开发者_JAVA技巧trictTo($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 :(
Ok, If you just want to replace characters, use preg_replace (Note, you can add any character with a few caviats.
- If you want to add
-
, it MUST be at the end of the list - If you want to add a
\
, it MUST be escaped by another\
- 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
}
精彩评论