2009-07-21 36 views

回答

3

隨着array_walk()你可以分開來寫你的標籤清洗功能,然後輕鬆地將其應用到您的傳入數據。

function sterilize(&$val,$key) 
{ 
    //do whatever security you need here 
    $val = trim($val); 
    $val = strip_tags($val); 
    //etc 
    return htmlspecialchars($val); 
} 
$bad_values = explode(',',$_GET['tags']); 
array_walk($bad_values,'sterilize'); 
1

嘗試以下操作:

function process_tags($tags) { 
    $tags = strip_tags($tags); 
    $tags = explode(',', $tags); 
    foreach($tags as $key => $value) { 
     $tags[$key] = htmlentities($tags[$key]); 
     $tags[$key] = trim($tags[$key]); 
    } 

    return $tags; 
} 

您可以直接調用該函數以下列方式:

$myTags = "apples, berries, oranges"; 
$tags = process_tags($myTags); 
+0

@ Chacha102:不,因爲你想修剪分隔符(`,`)。預先修剪不會那樣做。 – 2009-07-21 22:54:30

+0

啊......評論刪除魔術...... – 2009-07-21 22:55:04

1

使用array_map申請trim()htmlentities到陣列中的所有項目,你可以做一個行:

$tags = array_map('htmlentities', array_map('trim', explode(',', strip_tags($_GET["tags"])))); 
1

要小心,你是怎麼做到這一點。 HTML轉義是輸出任務,而不是您想要對您不打算立即打印到頁面的數據執行的操作。

我認爲這頁是有這樣的事情相當明確的,真正分開從逃逸的內容內容過濾

// First, get the tags as an array, filtered to be valid data 
$tags = array_map('filterTag', explode(',', $_GET['tags'])); 

// Do whatever other processing with $tags 

// NOW, create a version of the tags that you'll use for display only 
// or do this step ONLY just prior to display 
$tagsSafeForHtml = array_map('escapeForHtml', $tags); 

function filterTag($tag) 
{ 
    // Use whatever combination of filtering functions you want 
    return trim(strip_tags($value)); 
} 

function escapeForHtml($value) 
{ 
    // Use whatever escaping strategy that makes most sense for your content 
    return htmlspecialchars($value, ENT_COMPAT, 'UTF-8'); 
} 
相關問題