用正则表达式替换html标签

前端开发   发布日期:2025年07月18日   浏览次数:167

下面的代码用于修改html文本中的img标记,修改后的html适用于lazyload方式的图片加载:

  1. protected string LazyPicProcess(string content) {
  2. Regex re = new Regex("<\\s*img[\\s\\S]*?(?<src>src[\\s]*=[\\s]*[\"|\'](?<pic>[\\s\\S]*?)[\"|\'])[\\s\\S]*?>", RegexOptions.                  IgnoreCase);
  3. string str = re.Replace(content, new MatchEvaluator(ImgSrcReplace));
  4. return str;
  5. }
  6. public static string ImgSrcReplace(Match match) {
  7. string newtext = string.Empty;
  8. if (match.Groups.Count > ) {
  9. string img = match.Groups[].Value;
  10. string src = match.Groups["src"].Value;
  11. string pic = match.Groups["pic"].Value;
  12. newtext = img.Replace(src, "src=\"images/grey.gif\" data-img=\"" + pic + "\" isload=\"false\"");
  13. return newtext;
  14. }
  15. else {
  16. return match.Groups[].Value;
  17. }
    }

 

 

 

关于延迟加载图片参考博文:

JS图片延迟加载分析及简单的demo

 

以上就是用正则表达式替换html标签的详细内容,更多关于用正则表达式替换html标签的资料请关注九品源码其它相关文章!