需要处理点HTML内容,几个大家都熟知的软件使用、学习费时,自己写了两个函数。
处理HTML内容就是找标签,剔除,拿到需要的。作为码农,求人哪如求己。
太简单,无需正则介入。
Function1
//处理:或 形式内容
function Rep1(c,tag,new:String):String;
c:内容
tag:标签,p div span 等
new:替换的新内容
返回想要的内容。
Function2
//处理:形式内容
function Rep2(c,tag,new:String;DeletedContent:Boolean=false):String;
c:内容
tag:标签,p div span 等
new:替换的新内容
DeletedContent:是否删除改标签内容,默认否。
返回想要的内容。
function Rep1
function Rep1(c, tag, new: String): String;
var p1,p2:Integer;
s:String;
begin
result:= c;
p1:= pos('<'+tag,c);
while (p1 > 0) do
begin
p2:=pos('>',copy(Result,p1));
if p2<1 then
p2:=pos('/>',copy(Result,p1));
if p2>0 then
begin
s:=copy(Result,p1,p2);
result:=StringReplace(result,s,new,[rfReplaceAll, rfIgnoreCase]);
end;
p1:= pos('<'+tag,Result);
end;
end;
function Rep2
function Rep2(c, tag, new: String;DeletedContent:Boolean): String;
var
p1,p2:Integer; s:String;
begin
{<p > </p>}
result:= c;
p1:= pos('<'+tag,c);
while (p1 > 0) do
begin
if not deletedContent then
begin
p2:=pos('>',copy(Result,p1));
if p2>0 then
begin
s:=copy(Result,p1,p2);
result:=StringReplace(result,s,'',[rfReplaceAll, rfIgnoreCase]);
result:=StringReplace(result,'</'+tag+'>',new,[rfReplaceAll, rfIgnoreCase]);
end;
end
else
begin
p2:=pos('</'+tag+'>',copy(Result,p1));
if p2>0 then
begin
s:=copy(Result,p1,p2+length(tag)+2);
result:=StringReplace(result,s,'',[rfReplaceAll, rfIgnoreCase]);
end;
end;
p1:= pos('<'+tag,Result);
end;
end;
以上为Delphi实现。
@2021-03-19