8 YEARS AGO

Functions: Hyperlink removal

Below you can find a function that loops through all news items and removes all the hyperlinks from the NewsText field.

Below you can find a function that loops through all news items and removes all the hyperlinks from the NewsText field.
// Specify the query
string query = "select DocumentCulture, NodeID from View_CMS_News_Joined";

// Get the connection
CMS.DataEngine.GeneralConnection con = CMS.DataEngine.ConnectionHelper.GetConnection();

// Execute the query into a DataSet
System.Data.DataSet ds = con.ExecuteQuery(query, null, CMS.IDataConnectionLibrary.QueryTypeEnum.SQLQuery, false);

// Loop through the results
foreach (System.Data.DataRow row in ds.Tables[0].Rows) 
{    
    // Get the values from the record
    int nodeID = ValidationHelper.GetInteger(row["NodeID"], 0);
    string cultureCode = ValidationHelper.GetString(row["DocumentCulture"], "");

    // Get the current user info
    CMS.TreeEngine.TreeProvider tree = new CMS.TreeEngine.TreeProvider(CMSContext.CurrentUser);            
    CMS.TreeEngine.TreeNode node = null;

    // Get the document using the NodeID and the DocumentCulture
    if (nodeID > 0) 
    {
        node = CMS.WorkflowEngine.DocumentHelper.GetDocument(nodeID, cultureCode, tree);
    }
        
    // Get the text from the NewsText field
    string newsTextOriginal = ValidationHelper.GetString(node.GetValue("NewsText"), "");
    string newsTextNew = newsTextOriginal;    

    // Setup the regular expression
    string regex = @"<a[\s]+[^>]*?href[\s]?=[\s\""\']+(.*?)[\""\']+.*?>([^<]+|.*?)?<\/a>";
    System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(regex, System.Text.RegularExpressions.RegexOptions.IgnoreCase); 

    // Find the matches
    System.Text.RegularExpressions.MatchCollection matches = r.Matches(newsTextOriginal);

    // Loop through the matches
    foreach (System.Text.RegularExpressions.Match match in matches) 
    {
        // Remove the link by replacing the hyperlink with pure text
        newsTextNew = newsTextOriginal.Replace(match.Value, match.Groups[2].Value); 
    }

    // Update the node
    tree.UseCustomHandlers = false;
    node.SetValue("NewsText", newsTextNew);
    DocumentHelper.UpdateDocument(node, tree);
    
    // Optional: add workflow publishing
}