PHP code example of rokety / php-simple-html-purify

1. Go to this page and download the library: Download rokety/php-simple-html-purify 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/ */

    

rokety / php-simple-html-purify example snippets



use PHPSimpleHtmlPurify\Purifier;
use PHPSimpleHtmlPurify\Tag;

/div>';
$htmlPurifier = new Purifier();
$htmlPurifier->tagBlackList(new Tag('script'));//add script to tag blacklist rules
echo $htmlPurifier->purify($dirtyHtml);//output: <div><p>Hello Wrold</p></div>

$htmlPurifier = new Purifier();
$htmlPurifier->tagWhiteList(new Tag(['p', 'div']));//add p, div to tag whitelist rules
echo $htmlPurifier->purify($dirtyHtml);//output: <div><p>Hello Wrold</p></div>

//tag name also support regular expression, see source directory tests/*Test.php

$dirtyHtml = '<div style="color: #080808" class="data-content"><p>Hello World</p></div>';
$htmlPurifier = new Purifier();
$htmlPurifier->attrBlackList(new Attribute('class'));//add class to attribute blacklist, apply to all tag
echo $htmlPurifier->purify($dirtyHtml);//output: <div style="color: #080808" ><p>Hello World</p></div>

$dirtyHtml = '<div style="color: #080808" class="data-content"><p style="color: #101010">Hello World</p></div>';
$htmlPurifier = new Purifier();
$htmlPurifier->attrWhiteList(new Attribute('style', false, new Tag('div')));//add style to attribute whitelist, apply to div tag
echo $htmlPurifier->purify($dirtyHtml);//output: <div style="color: #080808" ><p style="color: #101010" >Hello World</p></div>

//attribute name also support regular expression, see source directory tests/*Test.php

$dirtyHtml = '<div style="color: #080808;position: absolute" class="data-content"><p style="color: #101010">Hello World</p></div>';
$htmlPurifier = new Purifier();
$htmlPurifier->attrValueBlackList(new AttributeValue('/position *: *absolute;?/', true, new Attribute('style')));//add style to attributeValue blacklist, apply to all tag
echo $htmlPurifier->purify($dirtyHtml);//output: <div style="color: #080808;"  class="data-content" ><p style="color: #101010" >Hello World</p></div>

$dirtyHtml = '<div style="color: #080808;position: absolute" class="data-content"><p style="color: #101010;font-size: 12px">Hello World</p></div>';
$htmlPurifier = new Purifier();
$htmlPurifier->attrValueWhiteList(new AttributeValue(['/color: *#\d+;?/', '/font-size: *\d+px;?/'], true, new Attribute('style', false, new Tag('div'))));//add style to attribute whitelist, apply to div tag
echo $htmlPurifier->purify($dirtyHtml);//output: <div style="color: #080808;"  class="data-content" ><p style="color: #101010; font-size: 12px" >Hello World</p></div>