テキストから HTML タグを取り除く方法
HTML マークアップを取り除いてプレーンテキストを取得します。内容を保持しつつ、文字エンティティも適切に処理します。
问题
HTML コンテンツがあり、タグやマークアップのないプレーンテキストが必要です。
前提条件
- HTML 構造の理解
- HTML エンティティに関する知識
ステップ
-
1. Parse the HTML
Use an HTML parser rather than a regex to strip tags. A parser correctly handles nested tags, attributes with > characters, and self-closing tags. Regex-based stripping can fail on edge cases like <script> blocks or attribute values containing >.
入力<p>Hello <b>world</b></p>输出parsed structure -
2. Extract text content
Walk the parsed DOM and collect text nodes. Skip script and style elements whose content is not visible text. Handle <br> as line breaks and <p> as paragraph breaks. The result is the visible text content.
入力<p>Hello <b>world</b></p>输出Hello world -
3. Decode HTML entities
After stripping tags, decode HTML entities (& → &, < → <, ' → ', → space). This recovers the original characters that were escaped in the HTML. Use a standard entity decoder for the full named and numeric entity set.
入力& < '输出& < '
期待される結果
HTML タグがすべて除去され、エンティティがデコードされたプレーンテキスト。
よくあるエラー
- Using regex to strip tags fails on edge cases
- Use a proper HTML parser. Regex cannot correctly handle nested tags, attributes with >, or CDATA sections.
- Script content appears in output
- Explicitly skip <script> and <style> elements when extracting text. Their content is code, not visible text.
トラブルシューティング指引
- If entities appear as literal text, run an entity decoder after stripping.
- If whitespace is wrong, normalize spaces and line breaks after extraction.
セキュリティ上の制限
- Stripping HTML tags prevents XSS in display contexts, but always also sanitize any remaining text for safe output.