views:

75

answers:

3

may be duplicate

I am using PHP and postgres.

How can I separate words in the form below? The maximun amount of words is 7.

word_1, word_2, word_3, ...
+4  A: 

You can call explode.

$string = 'word_1, word_2, ...';
$splitarr = explode(',' $string);

Then you can grab the values from the arr like so: $splitarr[0] ... $splitarr[6].

Split in this case is slightly slower than explode, as split takes a regular expression. http://blog.brianhartsock.com/2007/06/11/php-explode-vs-split/

Michael
+1  A: 

Don't bother with this. Just use PHP implode and explode functions and assembly/reformat the string to whatever you need.

Check this out:
http://matthom.com/archive/2005/06/22/code-mnemonics-php-implode-explode

Andrejs Cainikovs
+1  A: 

if words cannot contain any white space you can use the preg_split function:

$string="word_1, word_2, word_3"; 
$array=preg_split("/\s*,\s/",$string, PREG_SPLIT_NO_EMPTY);

if you use the PREG_SPLIT_NO_EMPTY constant you won't get empty results

mck89
Could you, please, give an example of how to use your code. I run unsuccessfully `echo array[0]`, since it prints all words separated by a comma. I would like to print only the word `word_1`.
Masi