아주 아주 해키 (정말 productionally 사용할 수 없습니다)하지만 :
이
기본적으로
Regex.Replace(input, @"<[^>]+?\/?>", m => {
// here you can exclude specific tags such as `<a>` or maybe `<b>`, etc.
return Regex.IsMatch(m.Value, @"^<a\b|\/a>$") ? m.Value : String.Empty;
});
C 번호, 그것은 단지 <a ...>...</a>
을 제외한 모든 HTML 코드를 꺼낸다 .
참고 :이 NOT합니까 :
태그가 제대로/중첩/개폐 된 검증 경우
- .
- 검증은
<>
실제로 HTML 태그 (어쩌면 당신의 입력 텍스트 자체에 <
또는 >
을 가지고?)
- 핸들 "중첩"
<>
태그 경우. 여기
이 도우미 메서드에있는 걸까요 같은 일이다 (예를 들어 <img src="http://placeholde.it/100" alt="foo<Bar>"/>
출력 문자열에 "/>
의 나머지를 떠나) :
// Mocks http://www.php.net/strip_tags
/// <summary>
/// Removed all HTML tags from the string and returned the purified result.
/// If supplied, tags matching <paramref name="allowedTags"/> will be left untouched.
/// </summary>
/// <param name="input">The input string.</param>
/// <param name="allowedTags">Tags to remain in the original input.</param>
/// <returns>Transformed input string.</returns>
static String StripTags(String input, params String[] allowedTags)
{
if (String.IsNullOrEmpty(input)) return input;
MatchEvaluator evaluator = m => String.Empty;
if (allowedTags != null && allowedTags.Length > 0)
{
Regex reAllowed = new Regex(String.Format(@"^<(?:{0})\b|\/(?:{0})>$", String.Join("|", allowedTags.Select(x => Regex.Escape(x)).ToArray())));
evaluator = m => reAllowed.IsMatch(m.Value) ? m.Value : String.Empty;
}
return Regex.Replace(input, @"<[^>]+?\/?>", evaluator);
}
// StripTags(input) -- all tags are removed
// StripTags(input, "a") -- all tags but <a> are removed
// StripTags(input, new[]{ "a" }) -- same as above
당신이 정규식을 통해이 작업을 수행하려는 경우 (태그 당) 다음을 기억하십시오. 규칙 1 : RegEx를 사용하여 HTML을 구문 분석하지 마십시오. 규칙 2 : RegEx를 사용하여 HTML을 구문 분석하려면 규칙 1을 참조하십시오. [RegEx는 일반 언어와 만 일치 할 수 있으며 HTML은 일반 언어와 일치하지 않습니다] (http://stackoverflow.com/a/590789/930393) – freefaller
@ 자유 낙하자는 저의 앞에 "신의 사랑을 위해,"아니오 통보로 거기 도착한 것처럼 보인다. :) –