如果应用程式是开放给公众使用, 过滤输入资料的字符十分重要, 在 PHP 可以透过正规表达式做特定字符的检查及过滤。
例如想将输入的资料里面全部非字母/数字的字符过滤可以这样做:
|
1 2 3 4 5 6 |
<?php $input = "this is a %%%&&& teting"; $cleaned = preg_replace("/[^A-Za-z0-9 ]/", "", $input); echo $cleaned; ?> |
这样会印出:
this is a teting
以上 preg_replace() 用的正规表达式会将英文字母, 数字及空格以外的其他字串过滤掉, 如果想将特别符号留下, 不想要字母, 数字及空格, 可以这样:
|
1 2 3 4 5 6 |
<?php $input = "this is a %%%&&& teting"; $cleaned = preg_replace("/[A-Za-z0-9 ]/", "", $search); echo $cleaned; ?> |
这样会印出:
%%%&&&