Tuesday, February 9, 2010

#1 2006-08-24 11:47:17 am

Bruce Phillips
Administrator
Registered: 2004-07-15
Posts: 2639

Split or Explode Text [String]

splitText:

Applescript:

-- delimiter : The delimiter used to split the text.
-- someText : The text to be split.
--
on splitText(delimiter, someText)
   set prevTIDs to AppleScript's text item delimiters
   set AppleScript's text item delimiters to delimiter
   set output to text items of someText
   set AppleScript's text item delimiters to prevTIDs
   return output
end splitText

-- Example
splitText(",", "a,b,c,d,e")

explode (similar to the PHP function):

Applescript:

-- delimiter : The delimiter used to split the text.
-- someText : The text to be split.
-- limit : If limit is set, the resulting list will contain a maximum of limit
-- elements with the last element containing the rest of someText.
-- If the limit parameter is negative, all elements except the last
-- -limit are returned.
--
on explode(delimiter, someText, limit)
   set limit to limit as integer
   
   set prevTIDs to AppleScript's text item delimiters
   set AppleScript's text item delimiters to delimiter
   set output to text items of someText
   
   if limit ≤ 0 then
       try
           if limit < 0 then set output to items 1 thru (limit - 1) of output
       on error
           set output to {}
       end try
   else if limit < ((count output) - 1) then
       set output to (items 1 thru limit of output) & ¬
           ("" & items (limit + 1) thru -1 of output)
   end if
   
   set AppleScript's text item delimiters to prevTIDs
   return output
end explode

-- Example
explode(",", "a,b,c,d,e", 2)

See also:
Join List [Implode]
explode_ignoring
http://brucep.net/code/applescript/split-text

Last edited by Bruce Phillips (2008-01-14 08:38:35 pm)

Offline

 

Board footer

Powered by FluxBB

[ Generated in 0.362 seconds, 8 queries executed ]

RSS (new topics) RSS (active topics)