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;
    }

 


 

posted on 2015-04-28 15:47  星星点灯6  阅读(1450)  评论(0编辑  收藏  举报