How to get excerpt correctly formatted

I'm using a theme that use the_excerpt() function to show the excerpt of the post.

All posts have not set custom excerpt, so the_excerpt() returns a piece of post content.

In some post first paragraph contains a br, for example:

pMy new question is:brwhy words are not separated by a white space?/p

The text rendered is:

My new question is:why words are not separated by a white space?

Following this post I implemented this solution:

function my_excerpt($text = '', $raw_excerpt = '') {
    add_filter('the_content', 'my_content', 6);

    // get through origin filter
    $text = wp_trim_excerpt($text);

    remove_filter('the_content', 'my_content', 6);
    return $text;
}
remove_filter( 'get_the_excerpt', 'wp_trim_excerpt');
add_filter( 'get_the_excerpt', 'my_excerpt');

function my_content($text)
{
    return str_replace( 'br', ' ', $text );
}

And this works, but I have two questions:

  1. Why the_excerpt() doesn't substitute br with space?
  2. Is there a better way to achieve this result?

Also, I'm quite new to wordpress development, any suggestions to improve my code are welcome.

Update: I found that is reported this issue, but unfortunately is still open.

Topic line-breaks the-content excerpt Wordpress

Category Web


wp_trim_excerpt() calls wp_trim_words() which applies wp_strip_all_tags() to the excerpt. The <br> tag is removed and not replaced with anything.

Not sure if this is feasible, but having a space after a colon is grammatically correct, and adding it to the original content would not affect the HTML, e.g.:

<p>My new question is: <br>why words are not separated by a white space?</p>

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.