Mega Code Archive

 
Categories / Delphi / Functions
 

PHP Alike implode & explode functions for Delphi

Title: PHP Alike implode & explode functions for Delphi Question: Implode & Explode routines just for Dephi making life easy ... Answer: ////////////////////////////////////////////////////////////////////////// // Procedure - implode // Author - Ronald Buster // Remarc - PHP like implode function // // Returns a string containing a string representation of all the array // elements in the same order, with the glue string between each element. ////////////////////////////////////////////////////////////////////////// function implode(const glue: string; const pieces: array of string): string; var I: Integer; begin Result := ''; for I := 0 to High(Pieces) do Result := Result + Glue + Pieces[I]; Delete(Result, 1, Length(Glue)); end; ////////////////////////////////////////////////////////////////////////// // Procedure - explode // Author - Ronald Buster // Remarc - PHP like explode function // // Returns an array of strings, each of which is a substring of string // formed by splitting it on boundaries formed by the string separator. // If limit is set, the returned array will contain a maximum of limit // elements with the last element containing the rest of string. // ////////////////////////////////////////////////////////////////////////// function explode(const separator, s: string; limit: Integer = 0): TDynStringArray; var SepLen: Integer; F, P: PChar; begin SetLength(Result, 0); if (S = '') or (Limit Exit; if Separator = '' then begin SetLength(Result, 1); Result[0] := S; Exit; end; SepLen := Length(Separator); P := PChar(S); while P^ #0 do begin F := P; P := AnsiStrPos(P, PChar(Separator)); if (P = nil) or ((Limit 0) and (Length(Result) = Limit - 1)) then P := StrEnd(F); SetLength(Result, Length(Result) + 1); SetString(Result[High(Result)], F, P - F); F := P; while (P^ #0) and (P - F Inc(P); end; end;