2012-08-09 21 views
1

我想從字符串中刪除禁止的字符。preg_match刪除禁止的字符?

$forbidden = array("<", ">", "{", "}", "[", "]", "(", ")", "select", "update", "delete", "insert", "drop", "concat", "script"); 
foreach ($forbidden as $forbidChar) { 
    if (preg_match("/$forbidChar/i", $string)) { 
     return TRUE; 
    } 
    return FALSE; 
} 

但它沒有按預期工作,我哪裏出錯了?

+0

你有'$ forbidden'正則表達式元字符。它不會工作,除非你逃脫它們。此外,這可以在一個正則表達式中完成。 – nickb 2012-08-09 12:56:31

+0

查看'preg_replace',並寫入'「/ $ forbidChar/i」'或者像這樣:''/'。$ forbidChar。'/ i'',我不確定這是否是個問題, $'符號在表達式中不是沒有意義的,所以它可能在這裏引起歧義,可能''/ {$ forbidChar}/i「'會起作用,但大括號也可能被認爲是不明確的。 – 2012-08-09 12:57:25

回答

2

你可以用一個正則表達式是這樣做的:

$forbidden = array(
      "<", ">", "{", "}", "[", "]", "(", ")", 
      "select", "update", "delete", "insert", "drop", "concat", "script"); 
$forbidden = array_map('preg_quote', $forbidden, array_fill(0, count($forbidden), '/')); 
return (bool) preg_match('/' . implode('|', $forbidden) . '/', $string); 

這正常逃脫所有的字符與preg_quote()和形成一個單一的正則表達式來測試所有的情況。

注:我沒有測試過,但它應該工作。

+0

完美運作! – Sarah 2012-08-09 13:10:04

2

如果要替換字符,則需要使用preg_replace()不是preg_match()

您可能還想確保使用preg_quote()正確地轉義您的禁止字符。

+1

感謝您的回覆,我不希望他們被替換,我只想返回是否有禁止的字符。 – Sarah 2012-08-09 12:54:57

+0

@Sarah在這種情況下,在傳遞變量之前使用'preg_quote()'。 – Matt 2012-08-09 13:10:14

1

可以使用performanter string_replace功能來做到這一點

<?php 
    $forbidden = array(
     "<", ">", "{", "}", "[", "]", "(", ")", 
     "select", "update", "delete", "insert", "drop", "concat", "script"); 

    $cleanString = str_ireplace($forbidden, "", $string); 
?> 
2

你需要躲避字符"[", "]", "(", ")" with "\[", "\]", "\)", "\)"

這裏是工作的代碼,

<?php 
$string = "dfds fdsf dsfs fkldsk select dsasd asdasd"; 
$forbidden = array(
      "<", ">", "{", "}", "\[", "\]", "\(", "\)", 
      "select", "update", "delete", "insert", "drop", "concat", "script"); 
    foreach ($forbidden as $forbidChar) { 
     if (preg_match("/$forbidChar/i", $string)) { 
      exit('Forbidden char dtected'); 
      return TRUE; 
     } 
     return FALSE; 
    } 
?> 
+0

我用preg_quote()來轉義字符。 – Sarah 2012-08-09 13:11:00

+0

好的。 preg_quote()最好使用。 – 2012-08-09 13:13:12