Replace Mailto-links
I've got this example string: var content = 'Lorem ipsum dolor sit amet info@xxx.com ipsum dolor
Solution 1:
If you have XHTML then use XElement as Chuck showed.
If not, then regular expressions are the way to go. Something like:
Regex find = new Regex("<a\\b[^>]*href=['\"]mailto:(.*?)['\"]", RegexOptions.Singleline|RegexOptions.IgnoreCase);
Warning, I did not test the above code but I'm 99% certain it is correct. Also, I may have missed a corner case such as a > in the email address.
Solution 2:
Convert the content to XML and then simply search for the a
tags that contain an href
that starts with mailto:
You'll need this using to use XPath: using System.Xml.XPath;
var content = "Lorem ipsum dolor sit amet <a href=\"mailto:info@xxx.com\">info@xxx.com</a> ipsum dolor <a href=\"mailto:info@yyy.eu\">info@yyy.eu</a> adipiscing elit.";
XElement x = XElement.Parse(string.Format("<root>{0}</root>", content));
var hrefs = x.XPathSelectElements("a[starts-with(@href, 'mailto:')]");
foreach (XElement href in hrefs)
{
href.Attribute("href").Value = "#";
href.Add(new XAttribute("title", "protected"));
string email = href.Value;
int at = email.IndexOf('@');
if(at > 0)
{
string username = email.Substring(0, at);
string domain = email.Substring(at);
if (username.Length > 2)
href.Value = string.Format("{0}..{1}",
username.Substring(0, 2), domain);
}
}
string result = string.Concat(x.Nodes().ToArray());
Post a Comment for "Replace Mailto-links"