0

I'm editing content that may be html in an EditText. Just before saving the result, I use Html.toHtml to convert the input into a string to be sent to the server. However this method call seems to be generating paragraph tags which I dont need. Eg -

Test edited
seems to get converted to 
<p dir="ltr">Test edited</p>

I would like to strip out the last paragraph tag before saving the content. If there are other paragraph tags, I would like to keep those. I have this regex that matches all p tags

"(<p.*>)(.*)(</p>)";

but I'm not sure how to match just the last paragraph and remove just the tags for it.

user1018916
  • 348
  • 4
  • 16

1 Answers1

1
public static void handleOneParagraph(SpannableStringBuilder text) {
   int start = 0;
   int end = text.length();
   String chars1 = "<p";

   if (end < 2)
   return;

    while (start < end  ) {
        String seq = text.toString().substring(start, start + 2);
        if (seq.equalsIgnoreCase(chars1))
            break;

        start++;
    }

    if (text.toString().substring(start, start + 2).equalsIgnoreCase(chars1) ) {

        int start2 = start + 1;
        String chars2 = ">";
        while (start2 < end && !text.subSequence(start2, start2+1).toString().equalsIgnoreCase(chars2) ) {
            start2++;
        }

        if (start2 >= end)
            return;

        text.replace(start, start2+1, "");

        end = text.length();

        start = end;


        String chars3 = "</p>";
        while (start > start2 + 4) {
            String last_p = text.subSequence(start - 4, start).toString();
            if (last_p.equalsIgnoreCase(chars3) ) {
                text.replace(start - 4, start, "");
                break;
            }
            start--;
        }

    }

}

And now, you can use it like this...

SpannableStringBuilder cleaned_text = new SpannableStringBuilder(Html.toHtml(your_text));
handleOneParagraph(cleaned_text);
chipaki
  • 52
  • 1
  • 4