How to quickly get tags in an array from a string?

I have $ _GET ['tags'] = "apples, oranges, bananas, grapes, cherries"

I need to put data in an array ( $ tags ).

What is a quick way to crop each element and perform security functions (removing html, special characters)?

+3
source share
4 answers

With array_walk (), you can write a tag cleanup function separately, and then easily apply it to your incoming data.

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');
+3
source

Try the following:

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;
}

You can simply call the function as follows:

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

array_map, trim() htmlentities ,

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

Be careful how you do it. HTML highlighting is an output task, not what you want to do with data that you are not going to print directly on the page.

I think that the pages will be fairly explicit in this matter and really separate content filtering from content escaping.

// 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' );
}
+1
source

Source: https://habr.com/ru/post/1713194/


All Articles