如何从字符串快速检索数组中的标签?

时间:2009-07-21 22:48:31

标签: php security arrays tags performance

我有$ _GET ['tags'] =“苹果,橘子,香蕉,葡萄,樱桃”

我需要将数据放入数组( $ tags )。

什么是快速修剪每个项目并执行安全功能(剥离html,特殊字符)?

4 个答案:

答案 0 :(得分: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 :(得分: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);

答案 2 :(得分:1)

使用array_maptrim()htmlentities应用于数组中的所有项目,您可以在一行中执行此操作:

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

答案 3 :(得分: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' );
}
相关问题