PHP code example of typo3 / html-sanitizer

1. Go to this page and download the library: Download typo3/html-sanitizer library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

typo3 / html-sanitizer example snippets



use TYPO3\HtmlSanitizer\Behavior;
use TYPO3\HtmlSanitizer\Behavior\NodeInterface;
use TYPO3\HtmlSanitizer\Sanitizer;
use TYPO3\HtmlSanitizer\Visitor\CommonVisitor;

tr('href'))
    ->addValues(new Behavior\RegExpAttrValue('#^https?://#'));

// attention: only `Behavior` implementation uses immutability
// (invoking `withFlags()` or `withTags()` returns new instance)
$behavior = (new Behavior())
    ->withFlags(Behavior::ENCODE_INVALID_TAG | Behavior::ENCODE_INVALID_COMMENT)
    ->withoutNodes(new Behavior\Comment())
    ->withNodes(new Behavior\CdataSection())
    ->withTags(
        (new Behavior\Tag('div', Behavior\Tag::ALLOW_CHILDREN))
            ->addAttrs(...$commonAttrs),
        (new Behavior\Tag('a', Behavior\Tag::ALLOW_CHILDREN))
            ->addAttrs(...$commonAttrs)
            ->addAttrs($hrefAttr->withFlags(Behavior\Attr::MANDATORY)),
        (new Behavior\Tag('br'))
    )
    ->withNodes(
        (new Behavior\NodeHandler(
            new Behavior\Tag('typo3'),
            new Behavior\Handler\ClosureHandler(
                static function (NodeInterface $node, ?DOMNode $domNode): ?DOMNode {
                    return $domNode === null
                        ? null
                        : new DOMText(sprintf('%s says: "%s"',
                            strtoupper($domNode->nodeName),
                            $domNode->textContent
                        ));
                }
            )
        ))
    );

$visitors = [new CommonVisitor($behavior)];
$sanitizer = new Sanitizer($behavior, ...$visitors);

$html = <<< EOH
<div id="main">
    <typo3>Inspiring People To Share</typo3>
    <!-- will be encoded, due to Behavior::ENCODE_INVALID_COMMENT -->
    <a class="no-href">invalidated, due to missing mandatory `href` attr</a>
    <a href="https://typo3.org/" data-type="url" wrong-attr="is-removed">TYPO3</a><br>
    (the <span>SPAN, SPAN, SPAN</span> tag shall be encoded to HTML entities)
</div>
EOH;

echo $sanitizer->sanitize($html);