tags:

views:

26

answers:

5

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 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']);
A: 

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

pop850
+3  A: 

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
Artefacto
Clever nestedness there! +1, but for a beginner, this may be confusing.
alex
this strips out my tags and still enters an empty value :(
pHpNUT
@pHp See here: http://codepad.viper-7.com/X5GReo
Artefacto
@alex You mean like "0"? Because that's about the only one. In any case, if he wants "0", he can specify a callback to `array_filter`.
Artefacto
@Artefacto Yeah sorry, I realised that quickly and deleted the comment.
alex
A: 

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.
phirschybar
There are a few mistakes there... `$new` will be null. And you are adding array members if the value is equal to an empty string.
alex
A: 

Will remove all empty array elements.

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

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"));
thomasrutter