0

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, ...
Community
  • 1
  • 1
Léo Léopold Hertz 준영
  • 134,464
  • 179
  • 445
  • 697
  • Dupe? http://stackoverflow.com/questions/470505/regular-expression-for-parsing-csv-in-php – Mark Biek Aug 07 '09 at 14:05
  • @Mark: The situation is different, since I need to first convert the data to `"word_1", "word_2", "word_3",...` from `word_1, word_2, word_3` such that whitespaces are removed between the words. before conversion. – Léo Léopold Hertz 준영 Aug 07 '09 at 14:18

3 Answers3

4

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/

Dirk
  • 6,774
  • 14
  • 51
  • 73
1

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
  • 27,428
  • 2
  • 75
  • 95
1

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
  • 294
  • 2
  • 5
  • 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`. – Léo Léopold Hertz 준영 Aug 07 '09 at 14:39