2011-04-27 18 views
2

我有一些來自telerik radeditor的html字符串,它可能包含具有寬度和高度的圖像標籤。我想刪除這些寬度和高度屬性。 我如何在代碼中使用正則表達式或其他在asp.net中做到這一點?在asp.net中刪除給定字符串中的img標籤的寬度和高度

+0

代碼示例? – JohnFx 2011-04-27 04:18:19

+0

請顯示一個示例html字符串和你想要的o/p。 – naveen 2011-04-27 04:44:35

回答

1

有很多的提到關於not to use regex when parsing HTML,所以你可以使用例如Html Agility Pack此:

HtmlDocument document = new HtmlDocument(); 
document.LoadHtml(html); 

var images = document.DocumentNode.SelectNodes("//img"); 
foreach (HtmlNode image in images) 
{ 
    if (image.Attributes["width"] != null) 
    { 
     image.Attributes["width"].Remove(); 
    } 
    if (image.Attributes["height"] != null) 
    { 
     image.Attributes["height"].Remove(); 
    } 
} 

這將移除了圖像widthheight屬性在你的HTML。

1

不知道我明白這個問題,但爲什麼不直接忽略它們而不是試圖去除它們呢?

在您的ASPX文件....

<img src="images/myimage.jpg"> 

而對於神的愛,不要試圖帶他們出去用正則表達式。

+0

爲什麼不使用正則表達式?真正感興趣。謝謝。 – 2012-07-17 15:16:03

+1

[因爲...](http://stackoverflow.com/a/1732454/30018) – JohnFx 2012-07-17 15:52:11

0

兩個正則表達式替換語句將做的工作相當不錯:

str = Regex.Replace(str, @"(<img[^>]*?)\s+height\s*=\s*\S+", 
     "$1", RegexOptions.IgnoreCase); 
str = Regex.Replace(str, @"(<img[^>]*?)\s+width\s*=\s*\S+", 
     "$1", RegexOptions.IgnoreCase); 

(這是一個C#代碼片段 - 不知道ASP.NET是一樣的)

-2
str = Regex.Replace(str, @"(<img[^>]*?)\s+height\s*=\s*\S+", 
     "$1", RegexOptions.IgnoreCase); 
str = Regex.Replace(str, @"(<img[^>]*?)\s+width\s*=\s*\S+", 
     "$1", RegexOptions.IgnoreCase); 
+3

這與Ridgerunner的減去文本的答案完全相同。 – 2011-07-07 07:56:18

相關問題