[PHP] 正規表達式 過濾特殊符號 / 過濾非字母數字的字元 / 過濾字母數字

如果應用程式是開放給公眾使用, 過濾輸入資料的字元十分重要, 在 PHP 可以透過正規表達式做特定字元的檢查及過濾。

過濾非字母/數字字元,取英文數字

<?php
 $input = "this is a %%%&&& apple";
 $cleaned = preg_replace("/[^A-Za-z0-9 ]/", "", $input);
 echo $cleaned;

?>
輸出
this is a apple

過濾字母/數字字元,取特殊自元

<?php
$input = "this is a %%%&&& apple";
$cleaned = preg_replace("/[A-Za-z0-9 ]/", "", $search);
echo $cleaned;
?>

輸出
%%%&&&

過濾特殊自元,取中文英文數字

<?php  $input = "this is a %%%&&& 帥哥";  $cleaned = preg_replace("[^A-Za-z0-9 \p{Han}]+/u", "", $input);
 echo $cleaned; ?>

輸出
this is a 帥哥

中間的 {Han} 表示中文字的意思。(記得行尾的 u,表示 unicode )
這樣子就可以 match 所有中文字,或是排除中文字等等。

參考網址:

留言

這個網誌中的熱門文章