String Functions to Get, Replace and Extract Fragments

Started by kevin, June 29, 2011, 04:10:26 PM

Previous topic - Next topic

kevin

   String Functions to Get, Replace and Extract Fragments

    Here's a couple of functions to help deal with string fragments.  These can be useful when cut'n'paste slabs of text together, For example these are used to 'chunk' the sections of the HTML together in the Dtab doc builder.   Quick and easy..

 
PlayBASIC Code: [Select]
   ; These are just some function to grab/remove and replace

; This is our text we're going to be running the functions on
s$ =" Bill went to the shop buy a pony. "

; display original text
print s$

; grab a string between two tags.
; without change the the name between the tags
Name$=GetFragment$(s$,"","")
print Name$

; Lets extract whatever is between those tags (inclusive)
Message$=ExtractFragment$(s$,"","")
print Message$


; Lets replace the stuff between the tags
Message$=ReplaceFragment$(s$,"","","JILL")
print Message$



Sync
waitkey


Psub GetFragment$(Page$,Opentag$,CloseTag$,StartPos=1)
Result$=""
StartPos=instring(Page$,OpenTag$,StartPos)
if StartPos>0
EndPos=instring(Page$,CloseTag$)
if EndPos>STartPOs
StartPos+=Len(Opentag$)
Result$=mid$(Page$,StartPos,EndPos-StartPos)
endif
endif
EndPsub Result$


Psub ExtractFragment$(Page$,Opentag$,CloseTag$)
page$=ReplaceFragment$(Page$,Opentag$,CloseTag$,"")
EndPsub page$


Psub ReplaceFragment$(Page$,Opentag$,CloseTag$,NewText$)
Fragment$=GetFragment$(Page$,Opentag$,CloseTag$)
Fragment$=Opentag$+fragment$+CloseTag$
Page$=replace$(Page$,Fragment$,NewText$)
EndPsub page$





Related Functions

      Encrypt Strings  / Simple Game Data Protection
     Entity Example (Loading Game Levels)
     Load File To String & Save String As File
     Load Text Files To String Array