开发者

Use Regex to replace HREFs

开发者 https://www.devze.com 2023-01-06 09:06 出处:网络
I have html email that I would like to track click activity. I need to update all hrefs within the email to point back to my server where they can be logged and redirected. Is there an easy way to do

I have html email that I would like to track click activity. I need to update all hrefs within the email to point back to my server where they can be logged and redirected. Is there an easy way to do this globally usin开发者_Go百科g .Net regex?

<a href="http://abc.com">ABC</a>

becomes

<a href="http://mydomain.com?uid=123&url=http:/abc.com>ABC</a>


Do not use a RegEx to parse HTML - it is not a regular language. See here for some compelling demonstrations.

Use the HTML Agility Pack to parse the HTML and replace the URLs.


Try the following code

public string ReplaceLinks(string emailSource) {
    string resultString = null;
    try {
        resultString = Regex.Replace(emailSource, "(<a href=\")(htt)", new MatchEvaluator(ComputeReplacement));
    } catch (ArgumentException ex) {
        // Syntax error in the regular expression
    }
    return resultString;
}

public String ComputeReplacement(Match m) {
    // You can vary the replacement text for each match on-the-fly
    return "$1http://mydomain.com?uid=123&url=$2";
}
0

精彩评论

暂无评论...
验证码 换一张
取 消