PHP: How do I get the explode() function to work with multiple separators in a row?
August 1, 2008 8:25 AM

PHP: How do I get the explode() function to work with multiple separators in a row?

I am using the explode Function on a string where there are multiple spaces after a word because it is tabbed. When I use explode as follows

$peices = explode(" ",$theData);

the $peices array does not record any of the data that comes after the section with multiples spaces. Any idea on how to get a complete array?
posted by kaozity to Computers & Internet (8 answers total) 1 user marked this as a favorite
I think you'll need to explain the problem more clearly. Give an example of $theData, and the array pieces you get out.

Are you talking about actual tabs, or multiple spaces? Because they're not the same thing - you would need to split on the string "\t" if the string uses tabs.
posted by le morte de bea arthur at 8:40 AM on August 1, 2008


Are there actually multiple spaces or an actual \t character? You can explode() on \t I believe, otherwise take a look at preg_split().
posted by Skorgu at 8:42 AM on August 1, 2008


The easiest way is probably to run a regular expression on it.


$array = preg_split("\s{2,}", $data);


This should get it if there are two or more spaces in a row. To split on a tab:


$array = preg_split("\t", $data);


This is untested, but it should work.
posted by sonic meat machine at 8:44 AM on August 1, 2008


The simplest way is to use preg_split on an arbitrary number of spaces, like preg_split("/\s+/", $my_string). For example:


<? var_dump(preg_split('/\s+/', "Test string this is a test")) ?>

array(6) {
[0]=>
string(4) "Test"
[1]=>
string(6) "string"
[2]=>
string(4) "this"
[3]=>
string(2) "is"
[4]=>
string(1) "a"
[5]=>
string(4) "test"
}

posted by pocams at 8:54 AM on August 1, 2008


Thank you,
It was the /t vs. spaces messing me up
posted by kaozity at 8:54 AM on August 1, 2008


Whoops, posting ate my multiple spaces. Here's a pastebin version. Note it will work for tabs, spaces, or other assorted whitespace.
posted by pocams at 8:55 AM on August 1, 2008


pocams, it works perfectly, thank you :-)
posted by kaozity at 9:43 AM on August 1, 2008


Heh, forgot my slashes. Damn regexes.
posted by sonic meat machine at 2:06 PM on August 1, 2008


« Older What are some examples of psychological studies...   |   What's the best resource to improve my Photoshop... Newer »
This thread is closed to new comments.