Getting rid of the #038; when string replacing content

I’m trying to add some string replacements to the_title() –

function format_title($content) {
    $content = str_replace('&','&<br>', $content);
    $content = str_replace('!','!<br>', $content);
    return $content;
}
add_filter('the_title','format_title',11);

When I try and replace ampersands I get an additional “#038;” after the replacement (ASCII for ampersand), I’m not sure as to why this occurs (security reason?) or how to create a workaround. I’ve tried replacing “&” with “& amp ;” but with no effect.

Read More

The goal is to add line breaks at certain points of a title to create a better flow in the typography.
Both the database and the site has UTF8 encoding.

Related posts

Leave a Reply

3 comments

  1. & is essentially synonym of &amp;. In the_title filter wptexturize() runs with priority 1 (important!) and makes this replacement.

    So by the time it gets to your format_title() at priority 11 – instead of replacing lone & symbol you replace (and break) chunk of & character entity.

    So you can:

    1. move your function to priority 0 and it will run before texturize
    2. leave priority at 11 but replace $#38; instead of just &
  2. This can also be caused by esc_url. You should use esc_url_raw instead, in this scenario.

    esc_url has this piece of code:

    // Replace ampersands and single quotes only when displaying.
    if ( $_context === 'display' ) {
        $url = wp_kses_normalize_entities( $url );
        $url = str_replace( '&amp;', '&', $url ); <!-- See this line!
        $url = str_replace( "'", ''', $url );
    }
    

    What esc_url_raw does is simply calling esc_url and skipping that conditional by passing a different context as argument.

  3. Here is one more solution:-

    wp-includesformatting.php >> esc_url ()  >>  comment the line <br> $url = str_replace( '&amp;', '&', $url ); 
    

    It works for me.