close

在網頁程式撰寫的時候,經常需要把使用者輸入的字串做過濾

但有些時候並非惡意攻擊字串

可能使用者只是輸入錯誤 

因此我們需要做一些基本的檢查來預防和提式

下面是使用 preg_match() 這個函數來檢查字串的方式

首先先簡單介紹一下 preg_match() 這個函數的用法

preg_match( 正則表達式 , 要比對的字串 , 比對結果)

其中比對結果是一個陣列,其中陣列結果是 $result[0]=原字串、$result[1]=第一個符合規則的字串、$result[2]=第二個符合規則的字串...以此類推

比對結果則回傳 1(正確) 或是 0(錯誤)

下面是一個簡單的範例

if(preg_match($regex, $resource , $result)) {

echo "OK";

} else {

echo "error";

}

另外附上幾個常用的表達式

 

//A. 檢查是不是數字

$standard_A = "/^([0-9]+)$/";

//B. 檢查是不是小寫英文

$standard_B = "/^([a-z]+)$/";

//C. 檢查是不是大寫英文

$standard_C = "/^([A-Z]+)$/";

//D. 檢查是不是全為英文字串

$standard_D = "/^([A-Za-z]+)$/";

//E. 檢查是不是英數混和字串

$standard_E = "/^([0-9A-Za-z]+)$/";

//F. 檢查是不是中文

$standard_F = "/^([\x7f-\xff]+)$/";

//G. 檢查是不是電子信箱格式

//$standard_G_1 這組正則允許 "stanley.543-ok@myweb.com"

//但 $standard_G_2 僅允許 "stanley543ok@myweb.com" ,字串內不包含 .(點)和 -(中線)

$standard_G_1 = "/^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/";

$standard_G_2 = "/^[\w]*@[\w-]+(\.[\w-]+)+$/" ;

//下面則是個簡單的範例,大家可以嘗試看看

 

$string = "stanley.543-ok@myweb.com" ;

$standard_G_1 = "/^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/";

$standard_G_2 = "/^[\w]*@[\w-]+(\.[\w-]+)+$/" ;

function checkString($strings, $standard){

if(preg_match($standard, $strings, $hereArray)) {

  return 1;

} else {

  return 0;

}

}

echo checkString($string, $standard_G_1);

echo "<br>";

echo checkString($string, $standard_G_2);

arrow
arrow
    全站熱搜

    風影淚 發表在 痞客邦 留言(0) 人氣()