代码之家  ›  专栏  ›  技术社区  ›  Alex L

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

  •  3
  • Alex L  · 技术社区  · 15 年前

    我有$\u get['tags']=“苹果、桔子、香蕉、葡萄、樱桃”

    我需要将数据放入一个数组中( 美元标签 )

    什么是 快速修剪每个项目并执行安全功能

    4 回复  |  直到 15 年前
        1
  •  3
  •   zombat    15 年前

    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');
    
        2
  •  1
  •   Andrew Moore    15 年前

    尝试以下操作:

    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);
    
        3
  •  1
  •   too much php    15 年前

    使用 array_map 申请 trim() htmlentities 对于数组中的所有项,可以在一行中执行此操作:

    $tags = array_map('htmlentities', array_map('trim', explode(',', strip_tags($_GET["tags"]))));
    
        4
  •  1
  •   Peter Bailey    15 年前

    小心你怎么做。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' );
    }