用正则表达式获取所有img标签

本文介绍了一种在HTML内容中查找并替换图片标签的ALT属性的方法。通过两种不同的函数实现,确保了图片即使没有原始ALT属性也能正确添加指定的标题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 public static string ReplaceOrAddImageTitle(string content, string title)
    {
        Regex reg = new Regex(@"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>", RegexOptions.IgnoreCase);
        MatchCollection mc = reg.Matches(content);

        string oldString = "", newString = "";
        if (mc.Count > 0)
            oldString = mc[0].Value;

        if (oldString.IndexOf("alt=") == -1)        
            newString = oldString.Replace("<img ", "<img  alt='" + title + "' ");
        content = content.Replace(oldString, newString);
        return content;
    }

 public static string ReplaceOrAddImageTitle1(string content, string title)
    {
        int startIndex = content.IndexOf("<img ");
        int endIndex = content.IndexOf(">", startIndex);
        string oldString = content.Substring(startIndex, endIndex - startIndex + 1);
        string newString = "";

        if (oldString.IndexOf("alt=") == -1)
            newString = oldString.Replace("<img ", "<img alt='" + title + "' ");
        else
        {
            startIndex = oldString.IndexOf("alt");
            int index1 = oldString.IndexOf("'");
            int index2 = oldString.IndexOf("\"");
            if (index1 < index2)
                endIndex = oldString.IndexOf("'", index1 + 1);
            else
                endIndex = oldString.IndexOf("\"", index2 + 1);

            string altStr = oldString.Substring(startIndex, endIndex - startIndex + 1);
            newString = oldString.Replace(altStr, " ").Replace("<img ", "<img alt='" + title + "' ");
        }
        content = content.Replace(oldString, newString);
        return content;
    }

 


 

转载于:https://www.cnblogs.com/pengzhihua/p/4463204.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值