Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to strip or escape html tags in Android

PHP has strip_tags function which strips HTML and PHP tags from a string.

Does Android have a way to escape html?

like image 904
Kris Avatar asked Jun 28 '11 06:06

Kris


People also ask

How do you escape HTML tags in HTML?

Escape characters will always begin with the ampersand symbol (&) and end with a semicolon symbol (;). The characters in between the ampersand and semicolon make up the specific code name or number for a particular character.

How do I strip a tag in HTML?

The strip_tags() function strips a string from HTML, XML, and PHP tags. Note: HTML comments are always stripped. This cannot be changed with the allow parameter. Note: This function is binary-safe.

How do I strip a string in HTML?

To strip out all the HTML tags from a string there are lots of procedures in JavaScript. In order to strip out tags we can use replace() function and can also use . textContent property, . innerText property from HTML DOM.

How can remove P tag from string in Android?

The HTML tags can be removed from a given string by using replaceAll() method of String class.


2 Answers

The solutions in the answer linked to by @sparkymat generally require either regex - which is an error-prone approach - or installing a third-party library such as jsoup or jericho. A better solution on Android devices is just to make use of the Html.fromHtml() function:

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).toString();     } else {        return Html.fromHtml(html).toString();     } } 

This uses Android's built in Html parser to build a Spanned representation of the input html without any html tags. The "Span" markup is then stripped by converting the output back into a string.

As discussed here, Html.fromHtml behaviour has changed since Android N. See the documentation for more info.

like image 108
Nick Street Avatar answered Sep 22 '22 16:09

Nick Street


Sorry for the late post, but i think this might help for others,

To just remove the html strips

Html.fromHtml(htmltext).toString() 

This way the html tag will be replaced with string, but the string willnot be formatted properly. Hence i did

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

This way i first replace with nextline with blankspace and removed blank space. Similarly you can remove others.

like image 35
yubaraj poudel Avatar answered Sep 20 '22 16:09

yubaraj poudel