2010/08/17

C# Html Tag 제거

특정 문자열,. 특히 Html 소스로 되어 있는 것중에 순수하게, 예를 들면 웹브라우져에서 보이는 문자열과 거의 같은 내용만 뽑아 내고자 할때...,

public string Strip(string text)
{
    return Regex.Replace(text, @"<(.|\n)*?>", string.Empty);
}

static Regex _htmlRegex = new Regex("<.*?>", RegexOptions.Compiled);
public static string StripTagsRegexCompiled(string source)
{
    return _htmlRegex.Replace(source, string.Empty);
}

public static string StripTagsCharArray(string source)
{
    char[] array = new char[source.Length];
    int arrayIndex = 0;
    bool inside = false;
    for (int i = 0; i < source.Length; i++)
    {
        char let = source[i];
        if (let == '<')
        {
            inside = true;
            continue;
        }
        if (let == '>')
        {
            inside = false;
            continue;
        }
        if (!inside)
        {
            array[arrayIndex] = let;
            arrayIndex++;
        }
    }
    return new string(array, 0, arrayIndex);
}

3가지 방법으로 해볼수가 있는데 가장 빠른 방법은 문자열 배열상태에서 잘라내기 입니다.

참조,.
http://aliraza.wordpress.com/2007/07/05/how-to-remove-html-tags-from-string-in-c/
http://dotnetperls.com/remove-html-tags

댓글 없음:

댓글 쓰기

가장 많이 본 글