Page 1 of 1

explode() - delimiting using comma OR space OR both

Posted: Sat Sep 01, 2007 12:32 am
by kkonline
Hi in an application i am working i require some tags (similar to flickr tags)
if the user enters tag:love,life,success
then i use

Code: Select all

$wordlist=explode(",",$tags);
to remove the tags string and put in an array each value and process. Delimited by comma

Now if the user writes tags: love ,life , success then the regex allows spaces and commas in addition to alphanumeric data.

Is there any way/solution such that i can explode (split a string) with delimiter comma OR space instead of just a comma as in

Code: Select all

$wordlist=explode(",",$tags);


"," delimits using only a comma

Code: Select all

$wordlist=explode(" ",$tags);

" " delimits using only a space

If there is space then also the array should be split. If there is a comma then also the array should split. And if there is a combination or comma space then too array should be split


Is there anyway i can check what is the delimiter either , or space or both and accordingly i can proceed?

Posted: Sat Sep 01, 2007 5:06 am
by Kieran Huggins
this sounds like a job for... Regular Expressions! preg_split() to be exact. in fact they have an example that does exactly what you're looking for on the PHP man page.

http://imgs.xkcd.com/comics/regular_expressions.png

feyd | we don't need a 95K image that's not important to the thread.

Re: explode() - delimiting using comma OR space OR both

Posted: Sat Sep 01, 2007 6:31 am
by superdezign
kkonline wrote:Is there any way/solution such that i can explode (split a string) with delimiter comma OR space instead of just a comma as in

Code: Select all

$wordlist=explode(",",$tags);


"," delimits using only a comma

Code: Select all

$wordlist=explode(" ",$tags);

" " delimits using only a space
To go either comma or space, you should check for a comma, then decide what to do. However, it's pretty senseless to mix the two. Just do commas, and trim the data.

Code: Select all

$data = explode(',', $content);
array_map("trim", $data);