{"id":16306765,"url":"https://github.com/oalders/html-restrict","last_synced_at":"2025-09-20T02:33:52.771Z","repository":{"id":666055,"uuid":"309179","full_name":"oalders/html-restrict","owner":"oalders","description":"HTML::Restrict - Strip away unwanted HTML tags","archived":false,"fork":false,"pushed_at":"2024-11-06T03:36:50.000Z","size":247,"stargazers_count":10,"open_issues_count":5,"forks_count":9,"subscribers_count":5,"default_branch":"main","last_synced_at":"2024-12-30T11:18:18.043Z","etag":null,"topics":["hacktoberfest","parse","perl","strip-html","unwanted-html-tags"],"latest_commit_sha":null,"homepage":"","language":"Perl","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/oalders.png","metadata":{"files":{"readme":"README.md","changelog":"Changes","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2009-09-16T21:40:05.000Z","updated_at":"2024-11-06T03:36:51.000Z","dependencies_parsed_at":"2024-10-28T14:28:43.886Z","dependency_job_id":"313154c9-558b-4d04-b6ed-036ccc5c2fab","html_url":"https://github.com/oalders/html-restrict","commit_stats":{"total_commits":175,"total_committers":12,"mean_commits":"14.583333333333334","dds":"0.13142857142857145","last_synced_commit":"ceefd0f2deab96fcd3b0ea8c50663b99cc7992c1"},"previous_names":[],"tags_count":28,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/oalders%2Fhtml-restrict","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/oalders%2Fhtml-restrict/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/oalders%2Fhtml-restrict/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/oalders%2Fhtml-restrict/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/oalders","download_url":"https://codeload.github.com/oalders/html-restrict/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":233619328,"owners_count":18703691,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["hacktoberfest","parse","perl","strip-html","unwanted-html-tags"],"created_at":"2024-10-10T21:11:34.515Z","updated_at":"2025-09-20T02:33:47.472Z","avatar_url":"https://github.com/oalders.png","language":"Perl","funding_links":[],"categories":[],"sub_categories":[],"readme":"# NAME\n\nHTML::Restrict - Strip unwanted HTML tags and attributes\n\n# VERSION\n\nversion v3.0.2\n\n# SYNOPSIS\n\n    use HTML::Restrict;\n\n    my $hr = HTML::Restrict-\u003enew();\n\n    # use default rules to start with (strip away all HTML)\n    my $processed = $hr-\u003eprocess('  \u003cb\u003ei am bold\u003c/b\u003e  ');\n\n    # $processed now equals: 'i am bold'\n\n    # Now, a less restrictive example:\n    $hr = HTML::Restrict-\u003enew(\n        rules =\u003e {\n            b   =\u003e [],\n            img =\u003e [qw( src alt / )]\n        }\n    );\n\n    my $html = q[\u003cbody\u003e\u003cb\u003ehello\u003c/b\u003e \u003cimg src=\"pic.jpg\" alt=\"me\" id=\"test\" /\u003e\u003c/body\u003e];\n    $processed = $hr-\u003eprocess( $html );\n\n    # $processed now equals: \u003cb\u003ehello\u003c/b\u003e \u003cimg src=\"pic.jpg\" alt=\"me\" /\u003e\n\n# DESCRIPTION\n\nThis module uses [HTML::Parser](https://metacpan.org/pod/HTML%3A%3AParser) to strip HTML from text in a restrictive\nmanner.  By default all HTML is restricted.  You may alter the default\nbehaviour by supplying your own tag rules.\n\n# CONSTRUCTOR AND STARTUP\n\n## new()\n\nCreates and returns a new HTML::Restrict object.\n\n    my $hr = HTML::Restrict-\u003enew()\n\nHTML::Restrict doesn't require any params to be passed to new.  If your goal is\nto remove all HTML from text, then no further setup is required.  Just pass\nyour text to the process() method and you're done:\n\n    my $plain_text = $hr-\u003eprocess( $html );\n\nIf you need to set up specific rules, have a look at the params which\nHTML::Restrict recognizes:\n\n- `rules =\u003e \\%rules`\n\n    Sets the rules which will be used to process your data.  By default all HTML\n    tags are off limits.  Use this argument to define the HTML elements and\n    corresponding attributes you'd like to use.  Essentially, consider the default\n    behaviour to be:\n\n        rules =\u003e {}\n\n    Rules should be passed as a HASHREF of allowed tags.  Each hash value should\n    represent the allowed attributes for the listed tag.  For example, if you want\n    to allow a fair amount of HTML, you can try something like this:\n\n        my %rules = (\n            a       =\u003e [qw( href target )],\n            b       =\u003e [],\n            caption =\u003e [],\n            center  =\u003e [],\n            em      =\u003e [],\n            i       =\u003e [],\n            img     =\u003e [qw( alt border height width src style )],\n            li      =\u003e [],\n            ol      =\u003e [],\n            p       =\u003e [qw(style)],\n            span    =\u003e [qw(style)],\n            strong  =\u003e [],\n            sub     =\u003e [],\n            sup     =\u003e [],\n            table   =\u003e [qw( style border cellspacing cellpadding align )],\n            tbody   =\u003e [],\n            td      =\u003e [],\n            tr      =\u003e [],\n            u       =\u003e [],\n            ul      =\u003e [],\n        );\n\n        my $hr = HTML::Restrict-\u003enew( rules =\u003e \\%rules )\n\n    Or, to allow only bolded text:\n\n        my $hr = HTML::Restrict-\u003enew( rules =\u003e { b =\u003e [] } );\n\n    Allow bolded text, images and some (but not all) image attributes:\n\n        my %rules = (\n            b   =\u003e [ ],\n            img =\u003e [qw( src alt width height border / )\n        );\n        my $hr = HTML::Restrict-\u003enew( rules =\u003e \\%rules );\n\n    Since [HTML::Parser](https://metacpan.org/pod/HTML%3A%3AParser) treats a closing slash as an attribute, you'll need to\n    add \"/\" to your list of allowed attributes if you'd like your tags to retain\n    closing slashes.  For example:\n\n        my $hr = HTML::Restrict-\u003enew( rules =\u003e{ hr =\u003e [] } );\n        $hr-\u003eprocess( \"\u003chr /\u003e\"); # returns: \u003chr\u003e\n\n        my $hr = HTML::Restrict-\u003enew( rules =\u003e{ hr =\u003e [qw( / )] } );\n        $hr-\u003eprocess( \"\u003chr /\u003e\"); # returns: \u003chr /\u003e\n\n    HTML::Restrict strips away any tags and attributes which are not explicitly\n    allowed. It also rebuilds your explicitly allowed tags and places their\n    attributes in the order in which they appear in your rules.\n\n    So, if you define the following rules:\n\n        my %rules = (\n            ...\n            img =\u003e [qw( src alt title width height id / )]\n            ...\n        );\n\n    then your image tags will all be built like this:\n\n        \u003cimg src=\"..\" alt=\"...\" title=\"...\" width=\"...\" height=\"...\" id=\"..\" /\u003e\n\n    This gives you greater consistency in your tag layout.  If you don't care about\n    element order you don't need to pay any attention to this, but you should be\n    aware that your elements are being reconstructed rather than just stripped\n    down.\n\n    As of 2.1.0, you can also specify a regex to be tested against the attribute\n    value. This feature should be considered experimental for the time being:\n\n        my $hr = HTML::Restrict-\u003enew(\n            rules =\u003e {\n                iframe =\u003e [\n                    qw( width height allowfullscreen ),\n                    {   src         =\u003e qr{^http://www\\.youtube\\.com},\n                        frameborder =\u003e qr{^(0|1)$},\n                    }\n                ],\n                img =\u003e [ qw( alt ), { src =\u003e qr{^/my/images/} }, ],\n            },\n        );\n\n        my $html = '\u003cimg src=\"http://www.example.com/image.jpg\" alt=\"Alt Text\"\u003e';\n        my $processed = $hr-\u003eprocess( $html );\n\n        # $processed now equals: \u003cimg alt=\"Alt Text\"\u003e\n\n    As of 2.3.0, the value to be tested against can also be a code reference.  The\n    code reference will be passed the value of the attribute, and should return\n    either a string to use for the attribute value, or undef to remove the attribute.\n\n        my $hr = HTML::Restrict-\u003enew(\n            rules =\u003e {\n                span =\u003e [\n                    { style     =\u003e sub {\n                        my $value = shift;\n                        # all colors are orange\n                        $value =~ s/\\bcolor\\s*:\\s*[^;]+/color: orange/g;\n                        return $value;\n                    } }\n                ],\n            },\n        );\n\n        my $html = '\u003cspan style=\"color: #0000ff;\"\u003eThis is blue\u003c/span\u003e';\n        my $processed = $hr-\u003eprocess( $html );\n\n        # $processed now equals: \u003cspan style=\"color: orange;\"\u003e\n\n- `trim =\u003e [0|1]`\n\n    By default all leading and trailing spaces will be removed when text is\n    processed.  Set this value to 0 in order to disable this behaviour.\n\n- `uri_schemes =\u003e [undef, 'http', 'https', 'irc', ... ]`\n\n    As of version 1.0.3, URI scheme checking is performed on all href and src tag\n    attributes. The following schemes are allowed out of the box.  No action is\n    required on your part:\n\n        [ undef, 'http', 'https' ]\n\n    (undef represents relative URIs). These restrictions have been put in place to\n    prevent XSS in the form of:\n\n        \u003ca href=\"javascript:alert(document.cookie)\"\u003eclick for cookie!\u003c/a\u003e\n\n    See [URI](https://metacpan.org/pod/URI) for more detailed info on scheme parsing.  If, for example, you\n    wanted to filter out every scheme barring SSL, you would do it like this:\n\n        uri_schemes =\u003e ['https']\n\n    This feature is new in 1.0.3.  Previous to this, there was no schema checking\n    at all.  Moving forward, you'll need to whitelist explicitly all URI schemas\n    which are not supported by default.  This is in keeping with the whitelisting\n    behaviour of this module and is also the safest possible approach.  Keep in\n    mind that changes to uri\\_schemes are not additive, so you'll need to include\n    the defaults in any changes you make, should you wish to keep them:\n\n        # defaults + irc + mailto\n        uri_schemes =\u003e [ 'undef', 'http', 'https', 'irc', 'mailto' ]\n\n- allow\\_declaration =\u003e \\[0|1\\]\n\n    Set this value to true if you'd like to allow/preserve DOCTYPE declarations in\n    your content.  Useful when cleaning up your own static files or templates. This\n    feature is off by default.\n\n        my $html = q[\u003c!doctype html\u003e\u003cbody\u003efoo\u003c/body\u003e];\n\n        my $hr = HTML::Restrict-\u003enew( allow_declaration =\u003e 1 );\n        $html = $hr-\u003eprocess( $html );\n        # $html is now: \"\u003c!doctype html\u003efoo\"\n\n- allow\\_comments =\u003e \\[0|1\\]\n\n    Set this value to true if you'd like to allow/preserve HTML comments in your\n    content.  Useful when cleaning up your own static files or templates. This\n    feature is off by default.\n\n        my $html = q[\u003cbody\u003e\u003c!-- comments! --\u003efoo\u003c/body\u003e];\n\n        my $hr = HTML::Restrict-\u003enew( allow_comments =\u003e 1 );\n        $html = $hr-\u003eprocess( $html );\n        # $html is now: \"\u003c!-- comments! --\u003efoo\"\n\n- create\\_newlines =\u003e \\[0|1\\]\n\n    Set the value to true if you'd like to have each br tag replaced by a\n    newline and every p tag replaced by two newlines. If a tag is\n    specified in the allowed HTML, it won't be replaced.\n\n- replace\\_img =\u003e \\[0|1|CodeRef\\]\n\n    Set the value to true if you'd like to have img tags replaced with\n    `[IMAGE: ...]` containing the alt attribute text.  If you set it to a\n    code reference, you can provide your own replacement (which may\n    even contain HTML).\n\n        sub replacer {\n            my ($tagname, $attr, $text) = @_; # from HTML::Parser\n            return qq{\u003ca href=\"$attr-\u003e{src}\"\u003eIMAGE: $attr-\u003e{alt}\u003c/a\u003e};\n        }\n\n        my $hr = HTML::Restrict-\u003enew( replace_img =\u003e \\\u0026replacer );\n\n    This attribute will only take effect if the img tag is not included\n    in the allowed HTML.\n\n- strip\\_enclosed\\_content =\u003e \\[0|1\\]\n\n    The default behaviour up to 1.0.4 was to preserve the content between script\n    and style tags, even when the tags themselves were being deleted.  So, you'd be\n    left with a bunch of JavaScript or CSS, just with the enclosing tags missing.\n    This is almost never what you want, so starting at 1.0.5 the default will be to\n    remove any script or style info which is enclosed in these tags, unless they\n    have specifically been whitelisted in the rules.  This will be a sane default\n    when cleaning up content submitted via a web form.  However, if you're using\n    HTML::Restrict to purge your own HTML you can be more restrictive.\n\n        # strip the head section, in addition to JS and CSS\n        my $html = '\u003chtml\u003e\u003chead\u003e...\u003c/head\u003e\u003cbody\u003e...\u003cscript\u003eJS here\u003c/script\u003efoo';\n\n        my $hr = HTML::Restrict-\u003enew(\n            strip_enclosed_content =\u003e [ 'script', 'style', 'head' ]\n        );\n\n        $html = $hr-\u003eprocess( $html );\n        # $html is now '\u003chtml\u003e\u003cbody\u003e...foo';\n\n    The caveat here is that HTML::Restrict will not try to fix broken HTML. In the\n    above example, if you have any opening script, style or head tags which don't\n    also include matching closing tags, all following content will be stripped\n    away, regardless of any parent tags.\n\n    Keep in mind that changes to strip\\_enclosed\\_content are not additive, so if you\n    are adding additional tags you'll need to include the entire list of tags whose\n    enclosed content you'd like to remove.  This feature strips script and style\n    tags by default.\n\n- `filter_text =\u003e [0|1|CodeRef]`\n\n    By default all text will be filtered to fix any encoding problems which may\n    cause security issues. You may override the encoding behaviour by providing\n    your own anonymous sub to `filter_text`. This first and only argument to the\n    sub is the text which needs to be filtered. The sub should return a scalar\n    containing the transformed text.\n\n        filter_text =\u003e sub {\n            my $text = shift;\n            ... # transform text\n            return $text;\n        },\n\n    You may also this value to 0 in order to disable this behaviour entirely.\n    Please be advised this is a security risk. Use caution when disabling this\n    parameter or providing your own filter function.\n\n# SUBROUTINES/METHODS\n\n## process( $html )\n\nThis is the method which does the real work.  It parses your data, removes any\ntags and attributes which are not specifically allowed and returns the\nresulting text.  Requires and returns a SCALAR.\n\n## get\\_rules\n\nAccessor which returns a hash ref of the current rule set.\n\n## get\\_uri\\_schemes\n\nAccessor which returns an array ref of the current valid uri schemes.\n\n# CAVEATS\n\nPlease note that all tag and attribute names passed via the rules param must be\nsupplied in lower case.\n\n    # correct\n    my $hr = HTML::Restrict-\u003enew( rules =\u003e { body =\u003e ['onload'] } );\n\n    # throws a fatal error\n    my $hr = HTML::Restrict-\u003enew( rules =\u003e { Body =\u003e ['onLoad'] } );\n\n# MOTIVATION\n\nThere are already several modules on the CPAN which accomplish much of the same\nthing, but after doing a lot of poking around, I was unable to find a solution\nwith a simple setup which I was happy with.\n\nThe most common use case might be stripping HTML from user submitted data\ncompletely or allowing just a few tags and attributes to be displayed.  With\nthe exception of URI scheme checking, this module doesn't do any validation on\nthe actual content of the tags or attributes.  If this is a requirement, you\ncan either mess with the parser object, post-process the text yourself or have\na look at one of the more feature-rich modules in the SEE ALSO section below.\n\nMy aim here is to keep things easy and, hopefully, cover a lot of the less\ncomplex use cases with just a few lines of code and some brief documentation.\nThe idea is to be up and running quickly.\n\n# SEE ALSO\n\n[HTML::TagFilter](https://metacpan.org/pod/HTML%3A%3ATagFilter), [HTML::Defang](https://metacpan.org/pod/HTML%3A%3ADefang), [MojoMojo::Declaw](https://metacpan.org/pod/MojoMojo%3A%3ADeclaw), [HTML::StripScripts](https://metacpan.org/pod/HTML%3A%3AStripScripts),\n[HTML::Detoxifier](https://metacpan.org/pod/HTML%3A%3ADetoxifier), HTML::Sanitizer, [HTML::Scrubber](https://metacpan.org/pod/HTML%3A%3AScrubber)\n\n# ACKNOWLEDGEMENTS\n\nThanks to Raybec Communications [http://www.raybec.com](http://www.raybec.com) for funding my\nwork on this module and for releasing it to the world.\n\nThanks also to the many other contributors. [https://github.com/oalders/html-restrict/graphs/contributors](https://github.com/oalders/html-restrict/graphs/contributors)\n\n# AUTHOR\n\nOlaf Alders \u003colaf@wundercounter.com\u003e\n\n# COPYRIGHT AND LICENSE\n\nThis software is copyright (c) 2009 by Olaf Alders.\n\nThis is free software; you can redistribute it and/or modify it under\nthe same terms as the Perl 5 programming language system itself.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Foalders%2Fhtml-restrict","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Foalders%2Fhtml-restrict","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Foalders%2Fhtml-restrict/lists"}