溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

C#實現(xiàn)文章添加內(nèi)鏈的方法

發(fā)布時間:2020-09-17 03:44:20 來源:腳本之家 閱讀:119 作者:realyrare 欄目:編程語言

為什么文章要添加內(nèi)鏈? 

1.有利于讀者

        我喜歡內(nèi)鏈文章的最初動機是讓讀者在我的博客獲得更好的閱讀體驗,并獲得更多的價值。如果我的讀者訪問了我的一篇文章,發(fā)現(xiàn)不僅僅回答他需要的答案,還提供了更多相關(guān)內(nèi)容的信息,讓他們能在更多的相關(guān)主題去擴展閱讀,他們遲早會喜歡并滿意我的博客。讓讀者滿意就是我們的目標(biāo),讀者他們滿意了,通常就會再次回訪(這讓你的博客變得有”粘性”)并和他們的朋友分享。

2.搜索引擎優(yōu)化(SEO)

      另外一個在你的博客相互鏈接文章的重要原因就是,搜索引擎在查看博客中鏈接的時候,既能找到內(nèi)容,又能有利于建立博客索引和提高博客內(nèi)容的排名。從其他外部博客建立的鏈接價值最高,能夠提高你在搜索引擎的排名,內(nèi)鏈雖然效果沒這么好,但是也是對排名有幫助的。

3.提升頁面瀏覽量

      在文章中增加鏈接能夠提高讀者訪問其他頁面內(nèi)容的機會,這帶來許多好處,首先它可以幫助您獲得更多的訪問者,如果你正在運行某種 CPM(按訪問人次收費)廣告,這是非常受益的。其次大量內(nèi)鏈給你的博客瀏覽者創(chuàng)造了一個博客內(nèi)容豐富的印象。我發(fā)現(xiàn),當(dāng)有人在你的博客上看到一個以上的頁面時,他們更容易記住它,訂閱它,評論它,并成為一個經(jīng)常和忠實的讀者。

而這三個好處看起來顯得作用不明顯,但是當(dāng)你擁有大量內(nèi)容的時候,它所能帶來的好處就是無法估量的。所以建議你從博客建立的時候就開始構(gòu)建內(nèi)鏈到站內(nèi)的其他文章,慢慢地這些內(nèi)鏈積累下來的好處將會產(chǎn)生非常明顯的好處。

 當(dāng)然還有更多好處,請自行百度知,說著說著有點跑偏主題了,我們主要說用C#怎么實現(xiàn)此功能,話不多說,上干貨??!

 第一種辦法:(string src指文本字符, IList<KeyWord> keys 指要匹配的關(guān)鍵詞庫集合) 

private string keyAddUrl(string src, IList<KeyWord> keys)
    {
      Regex reg = new Regex(@"(?i)(?:^|(?<!<a\b(?>[^<>]*))>)(?>[^<>]*)(?:<|$)");
      int length = 0;
      string temp = string.Empty;
      return reg.Replace(src, delegate (Match m)
      {
        temp = m.Value;
        length = temp.Length;
        for (int i = 0; i < keys.Count; i++)
        {
          string keyWordName = Regex.Escape(keys[i].KeyName);
          string keyWordUrl = Regex.Escape(keys[i].PCUrl);
          temp = Regex.Replace(temp, @"(?is)^((?:(?:(?!" + keyWordName + @"|</?a\b).)*<a\b(?:(?!</?a\b).)*</a>)*(?:(?!" + keyWordName +
            @"|</?a\b).)*)(?<tag>" + keyWordName + @")",
            @"$1<a href=""" rel="external nofollow" + keyWordUrl + @""" target=""_blank"" title=""${tag}"">${tag}</a>");
          if (length != temp.Length)
          {
            keys.Remove(keys[i]);
          }
          length = temp.Length;
        }
        return temp;
      });
    }

第二種辦法:(這是我自己能想到的辦法)   

/// <summary>
    /// 一鍵匹配內(nèi)鏈,只替換第一個匹配到的字符
    /// </summary>
    /// <param name="content">要匹配的文本字符</param>
    /// <param name="type">判斷類型是否是"編輯"</param>
    /// <returns></returns>
    [HttpPost]
    [ValidateInput(false)]
    public async Task<ActionResult> ContentReplace(string content, string type)
    {
      try
      {
        if (type == "edit")
        {
          content = WebHelper.ReplaceStrHref(content);
        }
        if (string.IsNullOrEmpty(content))
        {
          return Content("請輸入文本信息");
        }
        var list = await bll.GetAllList();
        if (list != null)
        {
          #region 第二種辦法
          // 第一次
          Regex reg = null;
          int n = -1;
          Dictionary<string, string> dic = new Dictionary<string, string>();
          for (int i = 0; i < list.Count; i++)
          {
            if (Regex.Match(content, list[i].KeyName).Success)
            {
              string pattern = $"<a href=\"{list[i].PCUrl}\" target=\"_blank\">{list[i].KeyName}</a>";
              reg = new Regex(list[i].KeyName);
              content = reg.Replace(content, pattern, 1);
              if (Regex.Match(content, pattern).Success)
              {
                //如果當(dāng)前關(guān)鍵字鏈接信息成功,將當(dāng)前的文本鏈接信息提取出來添加到字典中(dic),并以唯一標(biāo)識符代替文本鏈接信息作為占位符。
                reg = new Regex(pattern);
                n++;
                content = reg.Replace(content, "{" + n + "}", 1);
                dic.Add("{" + n + "}", pattern);
              }
            }
          }
          //將匹配到的文本鏈接信息format
          if (dic.Count != 0)
          {
            int m = -1;
            foreach (string key in dic.Keys)
            {
              m++;
              if (content.Contains("{" + m + "}"))
              {
                content = content.Replace("{" + m + "}", dic[key]);
              }
            }
          }
          #endregion
          content = WebHelper.RemoveStrImgAlt(content);
          return Content(content);
        }
        else
        {
          throw new Exception("關(guān)鍵字庫中沒有數(shù)據(jù),檢查集合是否拋異常了");
        }
      }
      catch (Exception ex)
      {
        throw ex;
      }
    }

此處也貼出上面WebHelper中的兩個方法:(關(guān)于作用方法都有注釋)

/// <summary>
    /// 移除文本字符的a標(biāo)簽
    /// </summary>  
    public static string ReplaceStrHref(string content)
    {
      var r = new Regex(@"<a\s+(?:(?!</a>).)*?>|</a>", RegexOptions.IgnoreCase);
      Match m;
      for (m = r.Match(content); m.Success; m = m.NextMatch())
      {
        content = content.Replace(m.Groups[0].ToString(), "");
      }
      return content;
    }
    /// <summary>
    /// 移除字符文本Img里面Alt關(guān)鍵字包裹的內(nèi)鏈
    /// </summary>   
    public static string RemoveStrImgAlt(string content)
    {
      Regex rg2 = new Regex("(?<=alt=\"<a[^<]*)</a>\"");
      if (rg2.Match(content).Success)
      {
        content = rg2.Replace(content, "");
      }
      Regex rg = new Regex("(?<=alt=\")<a href=\"[^>]*>");
      if (rg.Match(content).Success)
      {
        content = rg.Replace(content, "");
      }
      return content;
    }

總結(jié)

以上所述是小編給大家介紹的C#實現(xiàn)文章添加內(nèi)鏈的方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對億速云網(wǎng)站的支持!

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI