Forum Moderators: coopster

Message Too Old, No Replies

explode() - delimiting using comma OR space OR both

         

kkonline

5:28 am on Sep 1, 2007 (gmt 0)

10+ Year Member



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
$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

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

"," delimits using only a comma

$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.

ast0n

5:08 pm on Sep 1, 2007 (gmt 0)

10+ Year Member



You could use ereg_replace() to replace the spaces with commas, and then proceed to split as normal.

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

Putting in the string "love ,life , success" would result in "love,,life,,,success". Obviously you'd then have another problem: the multiple commas together, when exploded, would create blank values in the array. If you then use the following code:

for ($i=0, $j=0; isset($wordlist[$j]); $j++)
if ($wordlist[$j] <> "")
$wordlisttwo[$i++]=$wordlist[$j];

It'll cycle through $wordlist, and put all of the proper (non-null) values into a new array, $wordlisttwo.

Hope this helps!

dreamcatcher

5:44 pm on Sep 1, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Why not just use str_replace [php.net] to remove the spaces?

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

dc