explode() - delimiting using comma OR space OR both

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
kkonline
Forum Contributor
Posts: 251
Joined: Thu Aug 16, 2007 12:54 am

explode() - delimiting using comma OR space OR both

Post 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?
User avatar
Kieran Huggins
DevNet Master
Posts: 3635
Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:

Post 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.
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

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

Post 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);
Post Reply