PHPackages                             mb4it/htmlcleaner - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. mb4it/htmlcleaner

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

mb4it/htmlcleaner
=================

Modern HTML cleaner with selectors and fluent API

1.0.1(5mo ago)411MITPHPPHP &gt;=8.1

Since Jan 16Pushed 1mo agoCompare

[ Source](https://github.com/Dictator90/mb-htmlcleaner)[ Packagist](https://packagist.org/packages/mb4it/htmlcleaner)[ RSS](/packages/mb4it-htmlcleaner/feed)WikiDiscussions main Synced today

READMEChangelog (2)Dependencies (1)Versions (4)Used By (0)

PHP HTML Cleaner
================

[](#php-html-cleaner)

[Русская документация](README.ru.md)

MB HTML Cleaner is a powerful PHP package for cleaning and transforming HTML content. It provides a fluent interface for manipulating HTML structures, removing unwanted elements and attributes, normalizing content, and performing various HTML transformations.

Installation
------------

[](#installation)

Install the package via Composer:

```
composer require mb4it/htmlcleaner
```

Basic Usage
-----------

[](#basic-usage)

```
use MB\Support\HtmlCleaner\HtmlCleaner;

$cleaner = new HtmlCleaner();
$result = $cleaner->clean('Hello world!');
```

HtmlCleaner Methods
-------------------

[](#htmlcleaner-methods)

### stripEmptyTag()

[](#stripemptytag)

RemoveTransformer empty elements (with no text content or only whitespace) matching the given tag names.

```
// RemoveTransformer empty p tags
$result = $cleaner
    ->stripEmptyTag('p')
    ->clean($html);

// RemoveTransformer all empty elements
$result = $cleaner
    ->stripEmptyTag(null)
    ->clean($html);
```

HtmlCleaner Methods
-------------------

[](#htmlcleaner-methods-1)

### transform()

[](#transform)

Transform elements selected by the provided selectors using a TransformerInterface or closure. Supports CSS-like selectors for advanced element selection.

```
use MB\Support\HtmlCleaner\Selector\SelectorFacade;
use MB\Support\HtmlCleaner\Transformer\ReplaceTransformer;

// Basic tag selection
$result = $cleaner
    ->transform(
        SelectorFacade::tag('span'),
        ReplaceTransformer::tag('b')
    )
    ->clean($html);

// CSS-like selector syntax
$result = $cleaner
    ->transform(
        'div.container > p',
        ReplaceTransformer::tag('div')
    )
    ->clean($html);

// Multiple selectors with comma (OR)
$result = $cleaner
    ->transform(
        'strong, span.bold',
        ReplaceTransformer::tag('b')
    )
    ->clean($html);

// Attribute selectors
$result = $cleaner
    ->transform(
        'a[href^="/"]',
        function ($node) {
            $node->setAttribute('target', '_blank');
        }
    )
    ->clean($html);

// Pseudo-class selectors
$result = $cleaner
    ->transform(
        'div:has(p)',
        ReplaceTransformer::tag('section')
    )
    ->clean($html);

$result = $cleaner
    ->transform(
        'span:has-text("Hello")',
        ReplaceTransformer::tag('b')
    )
    ->clean($html);

// Class and attribute combinations
$result = $cleaner
    ->transform(
        'div.highlight[data-type="article"]',
        ReplaceTransformer::tag('article')
    )
    ->clean($html);
```

### transformAnd()

[](#transformand)

Apply transformation when all specified selectors match (logical AND).

```
use MB\Support\HtmlCleaner\Selector\SelectorFacade;

$result = $cleaner
    ->transformAnd([
        SelectorFacade::tag('span'),
        SelectorFacade::style('font-weight', 'bold')
    ], new ReplaceTransformer('strong'))
    ->clean($html);
```

### transformOr()

[](#transformor)

Apply transformation when any of the specified selectors match (logical OR).

```
$result = $cleaner
    ->transformOr([
        SelectorFacade::tag('b'),
        SelectorFacade::tag('strong')
    ], new ReplaceTransformer('strong'))
    ->clean($html);
```

### onlyText()

[](#onlytext)

Keep only text content of specified tags, removing all child elements.

```
// Keep text content of span and p tags
$result = $cleaner
    ->onlyText('span', 'p')
    ->clean($html);

// Keep text content of all elements
$result = $cleaner
    ->onlyText(null)
    ->clean($html);
```

### drop()

[](#drop)

RemoveTransformer entire elements matching the given tag names.

```
// RemoveTransformer script, style, and meta tags
$result = $cleaner
    ->drop('script', 'style', 'meta')
    ->clean($html);
```

### unwrap()

[](#unwrap)

UnwrapTransformer elements (remove the tag but keep its children) matching the given tag names.

```
// RemoveTransformer html and body tags, keeping their content
$result = $cleaner
    ->unwrap('span', 'font')
    ->clean($html);
```

### wrap()

[](#wrap)

WrapTransformer elements matching the given tag names with a new tag.

```
// WrapTransformer all span elements with a div
$result = $cleaner
    ->wrap('span', 'div')
    ->clean($html);
```

### allowStyles()

[](#allowstyles)

Allow only specific inline styles on elements.

```
// Allow only background-color and color styles
$result = $cleaner
    ->allowStyles('background-color', 'color')
    ->clean($html);
```

### stripStyles()

[](#stripstyles)

Strip specific inline styles from all elements.

```
// RemoveTransformer background and margin styles
$result = $cleaner
    ->stripStyles('background', 'margin')
    ->clean($html);
```

### stripAttributes()

[](#stripattributes)

RemoveTransformer specified attributes from all elements.

```
// RemoveTransformer class, id, and onclick attributes
$result = $cleaner
    ->stripAttributes('class', 'id', 'onclick')
    ->clean($html);
```

### changeAttr()

[](#changeattr)

Change attribute values for specific tags.

```
// Change href attribute of all a tags to "#"
$result = $cleaner
    ->changeAttr('a', 'href', '#')
    ->clean($html);

// Or

$result = $cleaner
    ->changeAttr('a', ['href' => '#', 'target' => '_blank'])
    ->clean($html);
```

### replaceTag()

[](#replacetag)

ReplaceTransformer one tag with another, copying all attributes and styles.

```
// ReplaceTransformer span tags with div tags
$result = $cleaner
    ->replaceTag('span', 'div')
    ->clean($html);
```

### normalizeWhitespace()

[](#normalizewhitespace)

Normalize whitespace within text nodes (collapse multiple spaces, trim).

```
$result = $cleaner
    ->normalizeWhitespace()
    ->clean($html);
```

### outputFragment()

[](#outputfragment)

Set output mode to return only an HTML fragment (no , etc.).

```
$result = $cleaner
    ->outputFragment()
    ->clean($html);
```

### outputDocument()

[](#outputdocument)

Set output mode to return a full HTML document.

```
$result = $cleaner
    ->outputDocument()
    ->clean($html);
```

### clean()

[](#clean)

Clean the provided HTML string according to the configured rules.

```
$result = $cleaner->clean($html);
```

Advanced Examples
-----------------

[](#advanced-examples)

### HTML Document Transformation

[](#html-document-transformation)

```
$html = 'body{margin:0;}Text example';

$result = $cleaner
    ->drop('style', 'meta', 'head')
    ->normalizeWhitespace()
    ->outputFragment()
    ->clean($html);

// Result: Text example
```

### Style-Based Transformation

[](#style-based-transformation)

```
$html = 'HelloWorld';

$result = $cleaner
    ->transform(
        SelectorFacade::style('font-weight', 'bold'),
        ReplaceTransformer::tag('b'),
        10
    )
    ->stripStyles('font-weight')
    ->clean($html);

// Result: HelloWorld
```

### Conditional Transformation with Closures

[](#conditional-transformation-with-closures)

```
$html = 'HelloWorld';

$result = $cleaner
    ->transform(
        SelectorFacade::style('font-weight', 'bold'),
        function (DomNode $node) {
            $doc = $node->ownerDocument;
            $parent = $node->parentNode;
            if (!$doc || !$parent) {
                return false;
            }

            $newNode = $doc->createElement('b');
            $newNode->setAttribute('class', 'changed');
            while ($node->firstChild) {
                $newNode->appendChild($node->firstChild);
            }

            $parent->replaceChild($newNode, $node);

            return true;
        }
    )
    ->clean($html);

// Result: HelloWorld
```

###  Health Score

38

—

LowBetter than 83% of packages

Maintenance83

Actively maintained with recent releases

Popularity9

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity46

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~2 days

Total

2

Last Release

166d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/75324054?v=4)[Maxim Bezvodinskikh](/maintainers/Dictator90)[@Dictator90](https://github.com/Dictator90)

---

Top Contributors

[![Dictator90](https://avatars.githubusercontent.com/u/75324054?v=4)](https://github.com/Dictator90 "Dictator90 (15 commits)")

---

Tags

htmlcleanproccess

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/mb4it-htmlcleaner/health.svg)

```
[![Health](https://phpackages.com/badges/mb4it-htmlcleaner/health.svg)](https://phpackages.com/packages/mb4it-htmlcleaner)
```

###  Alternatives

[voku/portable-ascii

Portable ASCII library - performance optimized (ascii) string functions for php.

576437.1M170](/packages/voku-portable-ascii)[voku/portable-utf8

Portable UTF-8 library - performance optimized (unicode) string functions for php.

52323.5M49](/packages/voku-portable-utf8)[spatie/laravel-html

A fluent html builder

8407.5M98](/packages/spatie-laravel-html)[ckeditor/ckeditor

JavaScript WYSIWYG web text editor.

5244.3M80](/packages/ckeditor-ckeditor)[caxy/php-htmldiff

A library for comparing two HTML files/snippets and highlighting the differences using simple HTML.

21522.3M22](/packages/caxy-php-htmldiff)[yajra/laravel-datatables-html

Laravel DataTables HTML builder plugin

29110.4M49](/packages/yajra-laravel-datatables-html)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
