Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Dave Wize's avatar

How to check if the html returned is just an empty tag.

Hi everyone. I have a chat system in place but it has an issue that If someone types just a space into the input (I use quilljs for the contentEditable) than it will record a empty p tag.

I want to check in the post create method in the only content is an empty tag so I can return early.

Or if someone has some REGEX to remove the outer tag if nothing is in it I would appriitate it. I do use REGEX to remove empty tags within the main p but the main element is not bieng filtered out, here is my current cleaner class.

<?php

namespace App\Classes;

use Stevebauman\Purify\Facades\Purify;

class HtmlCleaner
{
    public static function clean($html)
    {
        $cleaned = Purify::clean($html);
        $cleaned = str_replace('&nbsp;', ' ', $cleaned);
        do {
            $tmp = $cleaned;
            $cleaned = preg_replace(
                '#<([^ >]+)[^>]*>[[:space:]]*</>#',
                '',
                $cleaned
            );
        } while ($cleaned !== $tmp);

        return $cleaned;
    }
}
0 likes
6 replies
Nakov's avatar

Have you tried instructing the Purify library to remove the empty ones?

$config = ['AutoFormat.RemoveEmpty' => true];

$cleaned = Purify::config($config)->clean($html);

by default that's false you can change it here or in the config/purify.php file so it will apply everytime you use use the library.

Dave Wize's avatar

@Nakov thanks for your reply, but no, the outer tag still remain. only the inner tags are being removed

Nakov's avatar

@Dave Wize can you do a dd($html) before you pass it to the ->clean() function and share the content here?

Dave Wize's avatar

@Nakov Here is before and after the purify (most of the other empty tags were actually stripped out even beofre arriving at the Purify method probably by QuillJs)

<!--Before-->
<p>&nbsp;         &nbsp;&nbsp;         &nbsp;</p>
<!--After-->
<p>               </p>
Nakov's avatar
Nakov
Best Answer
Level 73

@Dave Wize okay, I fought a bit with it.. and this is how I did it:

$cleaned = Str::replace('<p>', '', $cleaned);
$cleaned = Str::replace('</p>', '', $cleaned);
$cleaned = trim(preg_replace('/[^(\x20-\x7F)\x0A\x0D]*/','', $cleaned));

at last the $cleaned will be completely empty string.. keep in mind that this removes the <p></p> just in order to see if there is any content at all in between, so you can use this for the check, but make sure that if the content is not empty then you return whatever the original one was.

Please or to participate in this conversation.