2015-11-18 29 views
1

我想知道是否有可能從字符串中去除特定的html標籤。免費帕斯卡帶僅從字符串中的一些HTML標籤

我想剝去只有<img>開頭的標籤。但所有的<img ...>內容都必須刪除。這是因爲我需要從字符串中刪除圖像。

我已經tryed去適應這個程序:

function StripHTML(S: string): string; 
var 
    TagBegin, TagEnd, TagLength: integer; 
begin 
    TagBegin := Pos('<', S);  // search position of first < 

    while (TagBegin > 0) do begin // while there is a < in S 
    TagEnd := Pos('>', S);    // find the matching > 
    TagLength := TagEnd - TagBegin + 1; 
    Delete(S, TagBegin, TagLength);  // delete the tag 
    TagBegin:= Pos('<', S);   // search for next < 
    end; 

    Result := S;     // give the result 
end; 

這種方式(改變兩行):

TagBegin := Pos('<img', S);  // search position of first < 
... 
TagBegin:= Pos('<img', S);   // search for next < 

但代碼落在一個牢不可破的循環。 :(

+1

你嘗試過什麼 – nicael

+0

我?編輯我的問題@nicael – Britto

+1

最簡單但並不是最快的方法是使用Pos/PosEx函數,如'i:= Pos('',html,i);刪除(html,i,j-i + 6);'while我或j不是0。 – Abelisto

回答

1

我申請從@Abelisto的技巧和它的工作現在 下面的代碼(我必須用引號將原來的代碼是在這裏找到: http://www.festra.com/eng/snip12.htm)。

function StripHTML(S: string): string; 
var 
    TagBegin, TagEnd : integer; 
begin 
    TagBegin := Pos('<img', S);  // search position of first < 

    while (TagBegin > 0) do begin // while there is a < in S 
    TagEnd := PosEx('>', S, TagBegin);    // find the matching > 
    Delete(S, TagBegin, (TagEnd - TagBegin) + 1);  // delete the tag 
    TagBegin:= Pos('<img', S);   // search for next < 
    end; 
    Result := S;     // give the result 
end;