JS:
function test() {
var str = "<img title=\"\" alt=\"\" align=\"\" src=\"/kindeditor/attached/image/20161214/20161214162554_8001.jpg\" width=\"312\" height=\"312\" />";
str += "<img title=\"\" alt=\"\" align=\"\" src=\"/kindeditor/attached/image/20161214/20161214162554_8001.jpg\" width=\"412\" height=\"412\" />";
str = str.replace(/ height="\d+"/g, " height=\"90\"");// “/”后面的是要替换的字符,“d\+”是数字,最后""里是用来填充的字符
str = str.replace(/ width="\d+"/g, " width=\"90\"");
alert(str);
}
<input type="button" id="hh" οnclick="test();" value="hell" />
C#:
var str = "<img title=\"\" alt=\"\" align=\"\" src=\"/kindeditor/attached/image/20161214/20161214162554_8001.jpg\" width=\"312\" height=\"312\" />";
str += "<img title=\"\" alt=\"\" align=\"\" src=\"/kindeditor/attached/image/20161214/20161214162554_8001.jpg\" width=\"412\" height=\"412\" />";
Regex reg = new Regex("width\\s*=\\s*\\S+ height\\s*=\\s*\\S+");
string result = reg.Replace(str, "width=\"90\" height=\"90\"");
第二种方法替换
//Regex reg1 = new Regex("height\\s*=\\s*\\S+");
//string result1 = reg1.Replace(result, "height=\"90\"");
处理多张图片中出现没有width height的情况:
//正则替换图片的宽高
Regex regImg = 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 matches = regImg.Matches(item.AdImg);
var relImg = string.Empty;
foreach (Match m in matches)
{
//进行匹配img是否存在width height
Regex reg = new Regex("width\\s*=\\s*\\S+ height\\s*=\\s*\\S+");
if (!reg.IsMatch(m.Value))//img 中不存在width height
{
//获取其他属性进行替换
Regex reg1 = new Regex("alt\\s*=\\s*\\S+");
relImg += reg1.Replace(m.Value, "style=\"width:90px;height:90px;\"");
}
else
{
relImg+= reg.Replace(m.Value, "style=\"width:90px;height:90px;\"");
}
}