开发者

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.

  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
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜