Search code examples
delphidelphi-xe8

removing duplicated text inside a string


i have string that got some text like this

str := 'Hi there My name is Vlark and this is my images <img src=""><img src=""> But This images need to be controlled <img src=""><img src=""><img src=""><img src="">'; 

this string have 6 images tags <img i wanted to control on this tags so if this string have more than 3 images tags leave the first three and remove the rest image tags . i couldnt figure out how can i do that in coding


Solution

  • Strategy:

    • Find position and length of complete enclosed tags: <img and >
    • If count larger than 3, remove tag.

    function RemoveExcessiveTags( const s: String): String;
    var
      tags,cP,p : Integer;
    begin
      tags := 0;
      cP := 1;
      Result := s;
      repeat
        cP := Pos('<img',Result,cP);
        if (cP > 0) then begin
         // Find end of tag
          p := Pos('>',Result,cP+4);
          if (p > 0) then begin
            Inc(tags);
            if (tags > 3) then begin // Delete tag if more than 3 tags
              Delete(Result,cP,p-cP+1);
            end
            else
              cP := p+1;  // Next search start position
          end
          else
            cP := 0;  // We reached end of string, abort search
        end;
      until (cP = 0);
    end;