Search code examples
phpwysiwygyii2htmlpurifierredactor

Remove empty tags in Imperavi Redactor


Using Imperavi Redactor with Yii 2 framework.

When no text is entered, Imperavi Redactor produces this markup: <p><br></p>. For each line break this markup is appended too.

I want to remove this because there is no way to normally validate such content with RequiredValidator. I want to do deletion in beforeValidate() event and check if any text is entered. If there is no text except empty tags, spaces and line breaks the saving is not allowed. Otherwise the content should be saved in initial condition.

It can be achieved with help of preg_replace, but I don't sure if it's the only variation generated by Redactor. And even it's the only variation such solution is not robust in case of switching the options (for example setting paragraphize option to false), updates or changing the WYSIWYG for example to TinyMCE or CKEditor.

For example, if it will be <p><br/></p> or <p>&nbsp;</p>, regex will fail. Also I want trim spaces, for example <p> <br></p>.

Is there option in Redactor to do that? removeEmpty option does not help.

I tried HTML Purifier with AutoFormat.RemoveEmpty option and the result was <p><br/></p> (for content <p></br></p>). Maybe we need to specify custom pattern or a list of tags what exactly should be deleted inside paragraphs.


Solution

  • Found this solution:

    use yii\helpers\HtmlPurifier;
    
    $text = HtmlPurifier::process($model->text, [
        'HTML.ForbiddenElements' => ['p', 'br', '&nbsp;'],
    ]);