I've been trying to add a filter in Wordpress to suppress empty paragraphs. I found a number of alternatives online (here is one of them https://gomakethings.com/remove-empty-paragraphs-added-by-wordpress/ ) but, so far, have failed miserably. After testing various hypothesis, I've found this strange regex behaviour happening:

I've created and tested this small script by itself (all it does is replace a space with a dash):

$content = 'abc def';
$patterns = array('#\s#');
$replacements = array('-');
$new_content = preg_replace($patterns, $replacements, $content); 
echo $new_content;

The result, predictably was:


Than I've added the same code as a filter in wordpress:

add_filter('the_content', array($this,'empty_paragraph_fix'),20,1);
function empty_paragraph($content) {
    $patterns = array('#\s*#');
    $replacements = array('-');
    $content = preg_replace($patterns, $replacements, $content);
    return $content;

But this time it gave me some very strange results. On a content that originally had something like this:

<div class="campus-list">
<ul class= ...

It returned this:


What am I missing here? Have you ever seen anything like this?

1 Answer 1


In your first example, your regex is \s, which will match a whitespace character. In the second example, you have \s*, which will match zero or more whitespace characters. You're probably looking for \s+, one or more whitespace characters.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.