Posted By

evanwalsh on 10/04/08


Tagged

array empty separator explode evan walsh


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

jamesming


Explode a string and return an array with no empty elements


 / Published in: PHP
 

URL: http://nothingconcept.com

  1. <?php
  2. /*
  3. Function: eexplode
  4.  
  5. Explodes an string and removes any empty
  6. elements in the resulting array
  7.  
  8. Parameters:
  9. $separator - The separator used to explode the $string
  10. $string - The string to explode
  11.  
  12. Returns:
  13. An array with no empty elements
  14.  
  15. Example:
  16. print_r(explode(":","evan:walsh:"));
  17.  
  18. Array(
  19. [0] => evan
  20. [1] => walsh
  21. [2] =>
  22. );
  23.  
  24. print_r(eexplode(":","evan:walsh:"));
  25.  
  26. Array(
  27. [0] => evan
  28. [1] => walsh
  29. );
  30.  */
  31. function eexplode($separator,$string){
  32. $array = explode($separator,$string);
  33. foreach($array as $key => $val){
  34. if(empty($val)){
  35. unset($array[$key]);
  36. }
  37. }
  38. return $array;
  39. }

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: koncept on October 5, 2008

You may be interested in mapping the exploded array with trim to avoid a situation like this:

print_r(eexplode(":","evan:walsh: :"));

Some thoughts:

function eexplode($separator,$string){
    $array = array_map('trim',explode($separator,$string));
    foreach($array as $key => $val){
        if($val == "") unset($array[$key]);
    }
    return array_values($array); // resets keys
}

print_r(eexplode(":",": : evan:walsh: :"));
Posted By: koncept on October 5, 2008

You could also do something like this, but it all depends on if you want to maintain breaks, spaces, tabs, etc ...


function eexplode($separator,$string) {
    return preg_split("/\s*${separator}\s*/",$string,-1,PREG_SPLIT_NO_EMPTY);
}
print_r(eexplode(':',"evan:\nwalsh:\n:\t:\x20:"));
Posted By: sultano on July 14, 2013

print_r(array_values(array_filter(explode(":","evan:walsh:"))));

You need to login to post a comment.