簡體   English   中英

如何在C#中將文本轉換為超鏈接?

[英]How do I convert text to hyperlinks in C#?

我對C#和ASP.NET開發非常非常新。

我想要做的是查找和替換網頁正文中出現的某些單詞。 每當正文中出現某個單詞時,我想將該單詞轉換為鏈接到我們網站上另一個頁面的超鏈接。

我不知道從哪里開始。 我找到了在C#中進行查找和替換的代碼,但是我沒有找到任何幫助,只需閱讀文檔,查找某些字符串,並將它們更改為不同的字符串。

有兩種方法可以實現這一目標。

string text = "We the People of the United States, in Order to form a more perfect Union, establish Justice, insure domestic Tranquility, provide for the common defence, promote the general Welfare, and secure the Blessings of Liberty to ourselves and our Posterity, do ordain and establish this Constitution for the United States of America.";

string augmentedText = text.Replace("provide", "<a href='#provide'>provide</a>");

您還可以使用正則表達式來完成此任務。

這是一個將每個單詞轉換為大寫的示例:

public static string MatchEval(Match m)
{
    return m.ToString().ToUpper();
}

static void Main(string[] args)
{
    string text = "This is some sample text.";

    Console.WriteLine(text);

    string result = Regex.Replace(text, @"\w+", new MatchEvaluator(MatchEval));

    Console.WriteLine(result);
}

希望這有幫助,祝你好運!

在文檔中查找單詞或文本的最佳作業是使用正則表達式。 如果您是這些人的新手,如果您打算讓您的項目具有高效性,我肯定會建議您通過它。

您可能還想在互聯網上搜索Wiki API,這將幫助您構建解決方案,而不必重新發明溫水。

我很確定以下鏈接將為您提供學習正則表達式的先機。 下載表達式測試器並稍微玩一下。

http://www.radsoftware.com.au/articles/regexlearnsyntax.aspx

看起來你想要做的是make ac#應用程序打開文件並查看源代碼。

您可能需要使用正則表達式來獲得要替換的文本的最佳匹配,在編寫此文本時還需要小心,以確保它只替換整個單詞,例如,如果您要為單詞創建鏈接湯姆帶你到湯姆斯頁面,你不希望這在明天的單詞等創建鏈接。

基本上我認為邏輯是找到前后有空格的單詞,並用超鏈接的代碼替換它。

當你第一次看到它時,正則表達式可能有點令人生畏,但是一旦你有了表達式,它就是一種非常強大的方式來執行這種事情。

如果您有一些特定的單詞,我們通常使用一些特殊的文本,如[NAME],[CLASS]來識別文本,然后執行以下操作,

  1. 使用textreader類讀取html,aspx文件。
  2. 將整個文本保存在字符串中並啟動字符串.replace(“[Name]”,@“...”)...將是必需的屬性,
  3. 將文本重新寫入具有相同擴展名的新頁面。

好的艾米麗,幫你解決一下你的短期限:

閱讀以下有關如何在代碼隱藏中獲取正文html內容的文章: http//west-wind.com/weblog/posts/481.aspx

假設您將Render()輸出存儲在名為_pageContent的變量中

我現在沒有使用任何正則表達式,因為我沒有時間正確地思考一個正則表達式。 你可以自己玩一下。 以下鏈接可能指向您的方向:正則表達式匹配多個字符串

public static void ChangeWordsToLinks()
{
  Dictionary<string, string> _wordLinkCollection = new Dicationary<string, string>();
  // fill the collection which will replace words by links here
  // Additionally you can fetch this from a database and loop 
  // through a DataTable to fill this collection
  _wordLinkCollection.add("foo", "http://www.foobar.com");
  _wordLinkCollection.add("bar", "http://www.barfoo.com");

  // this is lazy code and SHOULD be optimized to a single RegExp string.
  foreach(KayValuePair<string, string> pair in _wordLinkCollection)
  {
    _pageContent.Replace(String.Format(" {0} ", pair.Key), 
        String.Format("<a href='{0}'>{1}</a>", pair.Value, pair.Key));
  }
}

很高興,如果我可以幫助你

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM