2016-04-26 77 views
0

我試圖創建類似於bool系統堆棧溢出具有mvc控制器。如果我將最後一個或第一個dobbel星更改爲/ *之類的其他東西,那麼下面的代碼工作得很完美,但如果我希望兩者都是相同的呢? 像第一次**將是< b>,下次**將是</b>。相同的string.replace()在MVC控制器中給出了兩個不同的含義

[HttpPost] 
[ValidateInput(false)] 
public ActionResult Comment(Models.CommentModel s) 
    { 

     StringBuilder sbComments = new StringBuilder(); 
     sbComments.Append(HttpUtility.HtmlEncode(s.comment)); 

     sbComments.Replace("**", "&lt;b&gt;"); 
     sbComments.Replace("**", "&lt;/b&gt;"); 
     sbComments.Replace("&lt;b&gt;", "<b>"); 
     sbComments.Replace("&lt;/b&gt;", "</b>"); 

     s.comment = sbComments.ToString(); 

     var db = new WebApplication1.Models.ApplicationDbContext(); 

     if (ModelState.IsValid) 
     { 
      db.Comments.Add(s); 
      db.SaveChanges(); 
      return RedirectToAction("Comment"); 
     } 
     return View(s); 
    } 

我的解決方案感謝baiyangcao`s答案:

正則表達式可能看起來複雜,但它不是很難理解。 這個網站http://regexr.com/讓我很明白這一點。

public ActionResult Comment(Models.CommentModel s) 
    { 
     Regex fat = new Regex(@"\*\*(.*?)\*\*"); 
     Regex italic = new Regex(@"_(.*?)_"); 
     Regex largeText = new Regex(@"#(.*?)#"); 

     s.kommentar = HttpUtility.HtmlEncode(s.comment); 

     s.comment = largeText.Replace(s.comment, "<h1>$1</h1>"); 
     s.comment = fat.Replace(s.comment, "<b>$1</b>"); 
     s.comment = italic.Replace(s.comment, "<i>$1</i>"); 

     //this is the database I am adding my comments to 
     var db = new WebApplication1.Models.ApplicationDbContext(); 

     if (ModelState.IsValid) 
     {  
      db.Comments.Add(s); 
      db.SaveChanges(); 
      return RedirectToAction("Comment"); 
     } 
     return View(s); 
    } 

找不到Regex()?請記得在頁面頂部添加using System.Text.RegularExpressions;庫。

+0

的可能的複製[.NET - 服務器端降價到HTML轉換(http://stackoverflow.com/questions/448112 /淨的服務器端-降價到HTML轉換) – trailmax

回答

1

您可以嘗試使用正則表達式做了更換,這樣的:

Regex regexb = new Regex("\*\*(.*?)\*\*"); 
string comment = regexb.Replace(HttpUtility.HtmlEncode(s.comment), "<b>$1</b>"); 

希望這可以幫助

2

你可以使用這個擴展:

public static string replaceHipHip(this string text, string old, string hip, string hop) 
{ 
    var result = new StringBuilder(); 
    bool b = true; 
    int i = 0; 
    while(i>=0) 
    { 
     int j = text.IndexOf(old, i); 
     if (j == -1) 
     { 
      result.Append(text.Substring(i)); 
      break; 
     } 
     else 
     { 
      result.Append(text.Substring(i, j - i)); 
      if (b) 
       result.Append(hip); 
      else 
       result.Append(hop); 

      b ^= true; 
      i = j+old.Length; 
     } 
    } 
    return result.ToString(); 
} 

然後你可以寫:

string text = "Hello **this** is a **dummy** text"; 
Console.WriteLine(text.replaceHipHip("**", "<b>", "</b>")); 

,輸出:

你好虛擬文本

相關問題