Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions include/re_fmt.h
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ const char *pl_strstr(const struct pl *pl, const char *str);
int pl_trim(struct pl *pl);
int pl_ltrim(struct pl *pl);
int pl_rtrim(struct pl *pl);
void pl_strip_html(struct pl *pl);

/** Advance pl position/length by +/- N bytes */
static inline void pl_advance(struct pl *pl, ssize_t n)
Expand Down
48 changes: 48 additions & 0 deletions src/fmt/pl.c
Original file line number Diff line number Diff line change
Expand Up @@ -902,3 +902,51 @@ int pl_trim(struct pl *pl)

return err;
}


/**
* Strip HTML tags from a pointer-length string in-place
*
* @param pl Pointer-length string
*/
void pl_strip_html(struct pl *pl)
{
if (!pl)
return;

const char *r = pl->p;
bool in_tag = false;

/* lookup first possible html tag */
r = memchr(r, '<', pl->l);
if (!r)
return;

char *w = (char *)r;

/* Reference: https://html.spec.whatwg.org/multipage/parsing.html */
for (size_t len = pl->l - (size_t)(r - pl->p); len--; r++) {
if (in_tag) {
if (*r == '>')
in_tag = false;
continue;
}

/* 13.2.5.1 Data state */
if (*r == '<' && len >= 1) {
/* 13.2.5.6 Tag open state */
unsigned char n = *(r + 1);
if (isalpha(n) || n == '/' || n == '!' || n == '?') {
in_tag = true;
continue;
}
}

unsigned char c = (unsigned char)*r;
if (c >= 0x20 || c == '\n' || c == '\r' || c == '\t') {
*w++ = *r;
}
}

pl->l = (size_t)(w - pl->p);
}
8 changes: 8 additions & 0 deletions test/fmt.c
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,14 @@ int test_fmt_pl(void)
if (NULL != pl_strstr(&pl1, str0))
goto out;

/* pl_strip_html */
struct pl pl_html = PL_INIT;
char str_html[] = "abc <script>alert(1)</script> <= test <><a";
pl_set_str(&pl_html, str_html);
pl_strip_html(&pl_html);
TEST_EQUALS(23, pl_html.l);
TEST_EQUALS(0, pl_strcmp(&pl_html, "abc alert(1) <= test <>"));

return 0;
out:
return EINVAL;
Expand Down
Loading