PHPackages                             nedarta/yii2-clean-html-behavior - 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. [Validation &amp; Sanitization](/categories/validation)
4. /
5. nedarta/yii2-clean-html-behavior

ActiveYii2-extension[Validation &amp; Sanitization](/categories/validation)

nedarta/yii2-clean-html-behavior
================================

A Yii2 behavior to clean and sanitize HTML content in ActiveRecord attributes.

1.0.3.2(8mo ago)124MITPHP

Since Feb 6Pushed 4mo ago1 watchersCompare

[ Source](https://github.com/nedarta/yii2-clean-html-behavior)[ Packagist](https://packagist.org/packages/nedarta/yii2-clean-html-behavior)[ RSS](/packages/nedarta-yii2-clean-html-behavior/feed)WikiDiscussions main Synced today

READMEChangelog (6)Dependencies (2)Versions (7)Used By (0)

Yii2 Clean HTML Behavior
========================

[](#yii2-clean-html-behavior)

[![License](https://camo.githubusercontent.com/7013272bd27ece47364536a221edb554cd69683b68a46fc0ee96881174c4214c/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d626c75652e737667)](LICENSE)[![Packagist Version](https://camo.githubusercontent.com/ac8c090dd2f4e67e78a9a16e5f260e120769eaee8616cf05dc6ba6a5b53a4e9a/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6e6564617274612f796969322d636c65616e2d68746d6c2d6265686176696f72)](https://packagist.org/packages/nedarta/yii2-clean-html-behavior)

A Yii2 behavior that sanitizes and normalizes HTML attributes on ActiveRecord models. It runs automatically on `beforeValidate`, `beforeInsert`, and `beforeUpdate` to strip unsafe markup, fix spacing and punctuation, and optionally reformat line breaks while preserving emoji when required.

Features
--------

[](#features)

- Cleans HTML using Yii's `HtmlPurifier` with sensible defaults (nofollow links, `_blank` targets, no inline styles).
- Removes unwanted attributes (`class`, `style`, `id`, `dir`, `role`, `tabindex`, `contenteditable`, `spellcheck`, `attributionsrc`, `data-*`, `aria-*`).
- Normalizes punctuation spacing and collapses double spaces.
- Converts `` containers to paragraphs and unwraps `` tags.
- Optional emoji preservation via placeholder storage and restoration.
- Configurable handling for line breaks: keep ``, convert to paragraphs or lists, or strip entirely.

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

[](#installation)

Install the package via Composer:

```
composer require nedarta/yii2-clean-html-behavior
```

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

[](#basic-usage)

Attach the behavior to an ActiveRecord model and configure which attributes should be sanitized:

```
use nedarta\behaviors\CleanHtmlBehavior;

public function behaviors()
{
    return [
        [
            'class' => CleanHtmlBehavior::class,
            'attributes' => ['content', 'description'],
        ],
    ];
}
```

Configuration
-------------

[](#configuration)

OptionTypeDefaultDescription`attributes``array``[]` (required)List of ActiveRecord attributes to clean. Throws `InvalidConfigException` when empty.`htmlPurifierConfig``array`See belowConfiguration passed to `HtmlPurifier::process`. Defaults allow basic formatting tags and disable auto-paragraphing while stripping inline styles and enforcing `rel="nofollow"`/`target="_blank"`.`preserveLineBreaks``bool``true`When `false`, replaces `` tags with spaces or newlines before purification.`convertLineBreaks``stringfalse``false``keepEmoji``bool``false`Store emoji as placeholders before processing and restore them afterwards.### Default HtmlPurifier configuration

[](#default-htmlpurifier-configuration)

```
[
    'HTML.Allowed' => 'p,b,i,u,ul,ol,li,a[href],table,tr,td,th',
    'AutoFormat.RemoveEmpty' => true,
    'AutoFormat.RemoveEmpty.RemoveNbsp' => true,
    'AutoFormat.AutoParagraph' => false,
    'HTML.TargetBlank' => true,
    'Attr.AllowedFrameTargets' => ['_blank'],
    'HTML.Nofollow' => true,
    'CSS.AllowedProperties' => [],
]
```

Override only the keys you need:

```
public function behaviors()
{
    return [
        [
            'class' => CleanHtmlBehavior::class,
            'attributes' => ['content'],
            'htmlPurifierConfig' => [
                'HTML.Allowed' => 'p,b,i,u,ul,ol,li,a[href|title]',
            ],
        ],
    ];
}
```

Handling line breaks
--------------------

[](#handling-line-breaks)

You can control how `` tags and raw newlines are treated:

- **Preserve** (default): leaves `` tags untouched.
- **Strip**: set `preserveLineBreaks` to `false` and `convertLineBreaks` to `false` to collapse line breaks into spaces.
- **Paragraphs**: set `convertLineBreaks` to `'p'` to wrap newline-separated text into `` tags when no block markup is already present.
- **List**: set `convertLineBreaks` to `'ul'` to turn newline-separated lines into a bullet list when no block markup is present.

Emoji support
-------------

[](#emoji-support)

Set `keepEmoji` to `true` to temporarily replace emoji with placeholders during purification and restore them afterward, ensuring they are not stripped by the purifier.

Events
------

[](#events)

The behavior cleans configured attributes automatically during:

- `ActiveRecord::EVENT_BEFORE_VALIDATE`
- `ActiveRecord::EVENT_BEFORE_INSERT`
- `ActiveRecord::EVENT_BEFORE_UPDATE`

License
-------

[](#license)

This project is licensed under the MIT License. See [LICENSE](LICENSE) for details.

###  Health Score

34

—

LowBetter than 75% of packages

Maintenance69

Regular maintenance activity

Popularity9

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity43

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 ~54 days

Recently: every ~65 days

Total

6

Last Release

241d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/16962105?v=4)[Nedarta](/maintainers/nedarta)[@nedarta](https://github.com/nedarta)

---

Top Contributors

[![nedarta](https://avatars.githubusercontent.com/u/16962105?v=4)](https://github.com/nedarta "nedarta (13 commits)")

---

Tags

htmlPurifieryii2Behavior

### Embed Badge

![Health badge](/badges/nedarta-yii2-clean-html-behavior/health.svg)

```
[![Health](https://phpackages.com/badges/nedarta-yii2-clean-html-behavior/health.svg)](https://phpackages.com/packages/nedarta-yii2-clean-html-behavior)
```

###  Alternatives

[craftcms/cms

Craft CMS

3.6k3.6M3.1k](/packages/craftcms-cms)[stevebauman/purify

An HTML Purifier / Sanitizer for Laravel

5396.5M34](/packages/stevebauman-purify)[symfony/html-sanitizer

Provides an object-oriented API to sanitize untrusted HTML input for safe insertion into a document's DOM.

27941.7M142](/packages/symfony-html-sanitizer)[xemlock/htmlpurifier-html5

HTML5 support for HTML Purifier

1053.2M18](/packages/xemlock-htmlpurifier-html5)[paulzi/yii2-json-behavior

Yii2 json attribute behavior

75546.8k3](/packages/paulzi-yii2-json-behavior)[arogachev/yii2-many-to-many

Many-to-many ActiveRecord relation for Yii 2 framework

3643.1k4](/packages/arogachev-yii2-many-to-many)

PHPackages © 2026

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