Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove all empty values when I explode a string using PHP? [duplicate]

Tags:

php

I was wondering how can I remove all empty values when I explode a string using PHP for example, lets say a user enters ",jay,john,,,bill,glenn,,,"?

Thanks in advance for the help.

Here is part of the code that explodes user submitted values.

$tags = explode(",", $_POST['tag']); 
like image 838
snag Avatar asked Aug 07 '10 21:08

snag


People also ask

What does explode () do in PHP?

The explode() function breaks a string into an array. Note: The "separator" parameter cannot be an empty string. Note: This function is binary-safe.

How do you remove Blank values from an array?

Answer: Use the PHP array_filter() function You can simply use the PHP array_filter() function to remove or filter empty values from an array. This function typically filters the values of an array using a callback function.

How Reverse explode PHP?

PHP ImplodeThe implode function essentially does the opposite of the explode function. You can take an array and join it together and make it into one string instead of an array.


1 Answers

E.g. via array_filter() or by using the PREG_SPLIT_NO_EMPTY option on preg_split()

<?php // only for testing purposes ... $_POST['tag'] = ",jay,john,,,bill,glenn,,0,,";  echo "--- version 1: array_filter ----\n"; // note that this also filters "0" out, since (bool)"0" is FALSE in php // array_filter() called with only one parameter tests each element as a boolean value // see http://docs.php.net/language.types.type-juggling $tags = array_filter( explode(",", $_POST['tag']) );  var_dump($tags);  echo "--- version 2: array_filter/strlen ----\n"; // this one keeps the "0" element // array_filter() calls strlen() for each element of the array and tests the result as a boolean value $tags = array_filter( explode(",", $_POST['tag']), 'strlen' );  var_dump($tags);  echo "--- version 3: PREG_SPLIT_NO_EMPTY ----\n"; $tags = preg_split('/,/', $_POST['tag'], -1, PREG_SPLIT_NO_EMPTY); var_dump($tags); 

prints

--- version 1: array_filter ---- array(4) {   [1]=>   string(3) "jay"   [2]=>   string(4) "john"   [5]=>   string(4) "bill"   [6]=>   string(5) "glenn" } --- version 2: array_filter/strlen ---- array(5) {   [1]=>   string(3) "jay"   [2]=>   string(4) "john"   [5]=>   string(4) "bill"   [6]=>   string(5) "glenn"   [8]=>   string(1) "0" } --- version 3: PREG_SPLIT_NO_EMPTY ---- array(5) {   [0]=>   string(3) "jay"   [1]=>   string(4) "john"   [2]=>   string(4) "bill"   [3]=>   string(5) "glenn"   [4]=>   string(1) "0" } 
like image 102
VolkerK Avatar answered Sep 29 '22 13:09

VolkerK