[php] Explode string by one or more spaces or tabs

How can I explode a string by one or more spaces or tabs?

Example:

A      B      C      D

I want to make this an array.

This question is related to php regex explode

The answer is


This works:

$string = 'A   B C          D';
$arr = preg_split('/[\s]+/', $string);

The answers provided by other folks (Ben James) are quite good and I have used them. As user889030 points out, the last array element may be empty. Actually, the first and last array elements can be empty. The code below addresses both issues.

# Split an input string into an array of substrings using any set
# whitespace characters
function explode_whitespace($str) {  
  # Split the input string into an array
  $parts = preg_split('/\s+/', $str);
  # Get the size of the array of substrings
  $sizeParts = sizeof($parts);
  # Check if the last element of the array is a zero-length string
  if ($sizeParts > 0) {
    $lastPart = $parts[$sizeParts-1];
    if ($lastPart == '') {
      array_pop($parts);
      $sizeParts--;
    }
    # Check if the first element of the array is a zero-length string
    if ($sizeParts > 0) {
      $firstPart = $parts[0];
      if ($firstPart == '') 
        array_shift($parts); 
    }
  }
  return $parts;   
}

In order to account for full width space such as

full width

you can extend Bens answer to this:

$searchValues = preg_split("@[\s+ ]@u", $searchString);

Sources:

(I don't have enough reputation to post a comment, so I'm wrote this as an answer.)


The author asked for explode, to you can use explode like this

$resultArray = explode("\t", $inputString);

Note: you must used double quote, not single.


To separate by tabs:

$comp = preg_split("/[\t]/", $var);

To separate by spaces/tabs/newlines:

$comp = preg_split('/\s+/', $var);

To seperate by spaces alone:

$comp = preg_split('/ +/', $var);


Explode string by one or more spaces or tabs in php example as follow: 

   <?php 
       $str = "test1 test2   test3        test4"; 
       $result = preg_split('/[\s]+/', $str);
       var_dump($result);  
    ?>

   /** To seperate by spaces alone: **/
    <?php
      $string = "p q r s t";   
      $res = preg_split('/ +/', $string);
      var_dump($res);
    ?>


@OP it doesn't matter, you can just split on a space with explode. Until you want to use those values, iterate over the exploded values and discard blanks.

$str = "A      B      C      D";
$s = explode(" ",$str);
foreach ($s as $a=>$b){    
    if ( trim($b) ) {
     print "using $b\n";
    }
}

instead of using explode, try preg_split: http://www.php.net/manual/en/function.preg-split.php


I think you want preg_split:

$input = "A  B C   D";
$words = preg_split('/\s+/', $input);
var_dump($words);