开发者

PHP user entered data problem?

Okay when a user enters tags into the database I strip out HTML elements and separate tags by using a comma , But for some reason when I strip out the html tags an empty value is submitted into the database along with the other tags for example if a user enters the following data.

<html>,tag2,tag3,tag4 //an empty value is entered
,tag2,tag3,tag4 //this will also开发者_StackOverflow社区 enter an empty value

The html tag will be stripped but an empty value is submitted into the database how can I stop this from happening?

I think it has something to do with this part of my code.

$tags = explode(",", $_POST['tag']);


Try

array_filter( //remove elements that evaluate to FALSE (includes empty ones)
    array_map('trim', //trim space around tags
        array_map('strip_tags', //remove html tags from the... tags
            explode(",", $_POST['tag'])))); //separate on comma


Here's a link to a function that'll remove the empty elements in a PHP array: http://www.bitrepository.com/remove-empty-values-from-an-array-in-php.html


This will remove the blank tags:

$tags = explode(",", $_POST['tag']);
$new_set  = array();

foreach ($tags as $tag){

  if ($tag == ''){

    $new_set[] = $tag;
  }
}

$tags = implode(',', $new);

// now store $tags into your database.


Will remove all empty array elements.

 foreach($tags as $key => $tag) {
   if (empty($tag)) unset($tags[$key]);
 }


If you run

explode(",", ",apple,pear,banana");

You'll get an array like this one:

array('', 'apple', 'pear', 'banana');

The explode() function splits the string whereever there is a comma. There are three commas, which means it will split the string into four. Because there is nothing before the first comma in the input string, it means the first result will be an empty string.

If you don't want this, you'll need to filter out any empty strings from the result of explode(). You can use array_filter() for this:

array_filter(explode(",", ",apple,pear,banana"));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜