Cómo quitar o escapar etiquetas html en Android


PHP tiene la función strip_tags que elimina las etiquetas HTML y PHP de una cadena.

¿Android tiene una manera de escapar de html?

Author: Junior M, 2011-06-28

7 answers

Las soluciones en la respuesta enlazada por @sparkymat generalmente requieren regex - que es un enfoque propenso a errores-o instalar una biblioteca de terceros como jsoup o jericho. Una mejor solución en dispositivos Android es solo hacer uso del Html.Función fromHtml ():

public String stripHtml(String html) {
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
       return Html.fromHtml(html, Html.FROM_HTML_MODE_LEGACY);
    } else {
       return Html.fromHtml(html);
    }
}

Utiliza el analizador Html integrado de Android para crear una representación Spanned del html de entrada sin etiquetas html. El marcado" Span " se elimina convirtiendo la salida de nuevo en una cuerda.

Como se discutió aquí, Html.El comportamiento de fromHtml ha cambiado desde Android N. Consulte la documentación para obtener más información.

 208
Author: Nick Street,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:34:41

Lo siento por el post tardío, pero creo que esto podría ayudar a otros,

Para simplemente eliminar las tiras html

Html.fromHtml(htmltext).toString()

De esta manera la etiqueta html será reemplazada por string, pero la string no será formateada correctamente. Por lo tanto lo hice

Html.fromHtml(htmltext).toString().replaceAll("\n", "").trim()

De esta manera, primero reemplazo con nextline con espacio en blanco y eliminé el espacio en blanco. Del mismo modo, puede eliminar otros.

 12
Author: yubaraj poudel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-07 09:10:44

También puede usar Html.escapeHtml(String) si se dirige a API 16 o superior.

Para segmentar también por debajo de la API 16, puedes usar la siguiente clase llamando a HtmlUtils.escapeHtml(String) que simplemente saqué de la fuente de Html.escapeHtml(String).

public class HtmlUtils {

    public static String escapeHtml(CharSequence text) {
        StringBuilder out = new StringBuilder();
        withinStyle(out, text, 0, text.length());
        return out.toString();
    }

    private static void withinStyle(StringBuilder out, CharSequence text,
                                    int start, int end) {
        for (int i = start; i < end; i++) {
            char c = text.charAt(i);

            if (c == '<') {
                out.append("&lt;");
            } else if (c == '>') {
                out.append("&gt;");
            } else if (c == '&') {
                out.append("&amp;");
            } else if (c >= 0xD800 && c <= 0xDFFF) {
                if (c < 0xDC00 && i + 1 < end) {
                    char d = text.charAt(i + 1);
                    if (d >= 0xDC00 && d <= 0xDFFF) {
                        i++;
                        int codepoint = 0x010000 | (int) c - 0xD800 << 10 | (int) d - 0xDC00;
                        out.append("&#").append(codepoint).append(";");
                    }
                }
            } else if (c > 0x7E || c < ' ') {
                out.append("&#").append((int) c).append(";");
            } else if (c == ' ') {
                while (i + 1 < end && text.charAt(i + 1) == ' ') {
                    out.append("&nbsp;");
                    i++;
                }

                out.append(' ');
            } else {
                out.append(c);
            }
        }
    }
}

Estoy usando esta clase que funciona bien.

 9
Author: Buddy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-17 00:39:00

Esto es para el nuevo método alternativo (API 16+):

android.text.Html.escapeHtml(your_html).toString();
 4
Author: Tomero Indonesia,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-09 14:30:15
 Spanned spanned;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            spanned = Html.fromHtml(textToShare, Html.FROM_HTML_MODE_LEGACY);
        } else {
            spanned = Html.fromHtml(textToShare);
        }
tv.setText(spanned.toString());
 2
Author: Atif Mahmood,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-15 07:18:03

Esto es muy simple con jsoup

public static String html2text(String html) {
   return Jsoup.parse(html).text();
}
 1
Author: Jayakrishnan PM,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-10 10:43:49

Html.fromHtml puede ser extremadamente lento para cadenas html grandes.

Así es como puedes hacerlo, fácil y rápido con jsoup:

Agrega esta línea a tu archivo gradle:

implementation 'org.jsoup:jsoup:1.11.3'

Compruebe cuál es la última versión de jsoup aquí: https://jsoup.org/download

Añade esta línea a tu código:

String text = Jsoup.parse(htmlStr).text();

Revise este enlace aquí para aprender cómo preservar los saltos de línea:

Cómo conservo los saltos de línea cuando uso jsoup para convertir html a plano ¿mensaje?

 1
Author: live-love,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-08 19:17:15