如果應用程式是開放給公眾使用, 過濾輸入資料的字元十分重要, 在 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; ?> |
這樣會印出:
%%%&&&