Explode

From Director Online Wiki
Jump to: navigation, search
Based on PHP's [explode] function.
 -- Examples:
 --
 --    put explode("your", "cleanyourhead")
 --    -- ["clean", "head"]
 --
 --    put explode("r", "cleanyourhead")
 --    -- ["cleanyou", "head"]
 --
 --    put explode("y", "cleanyourhead")
 --    -- ["clean", "ourhead"]
 --
 on explode delimStr, str, limit

   if (the paramCount = 0) then return "Usage:" &RETURN &"-- explode(delimStr, str, limit)" 
   if delimStr = "" then return FALSE  
   if NOT str contains delimStr then return [str]
   
   set myArray = []
   
   set delimOffset = offset(delimStr, str)
   repeat while delimOffset > 0
	 
	 if integerP(limit) then
	   
	   if (count(myArray) < limit - 1) then
		 
                 -- Issue when the delimiter is in the begin of the string
                 if delimOffset = 1 then
                     set myItem = "" 
                 else   
                     set myItem = char 1 to delimOffset - 1 of str  
                 end if
		 --set myItem = char 1 to delimOffset - 1 of str  

		 delete char 1 to delimOffset + length(delimStr) - 1 of str
		 add myArray, myItem
		 
	   else exit repeat
	   
	 else -- No limit, so just drive on.

           -- Issue when the delimiter is in the begin of the string
           if delimOffset = 1 then
               set myItem = "" 
           else   
               set myItem = char 1 to delimOffset - 1 of str  
           end if
           --set myItem = char 1 to delimOffset - 1 of str  
	   delete char 1 to delimOffset + length(delimStr) - 1 of str
	   add myArray, myItem  
	   
	 end if
	 
	 set delimOffset = offset(delimStr, str)
	 
   end repeat 
   
   if (length(str) > 0) then 
	 add myArray, str
	 set str = ""
   end if
   
   return myArray
   
 end
--[[User:Cole|CBT]] 13:18, 12 Oct 2005 (MDT)