phpwordpressreplace

Can't replace wp_get_document_title() text with search string containing hyphen


i have a wordpress installation and this part of code below:

$maintitle = " – " . get_bloginfo( 'name' );
$res = str_replace($maintitle, "", wp_get_document_title());

The goal is to cut the title in Wordpress, and show the truncated version somewhere on page.

So, if my wp_get_document_title() returns Gallery – Some Site and get_bloginfo( 'name' ) returns Some Site, I expect to see as a result - Gallery.

Of course, it is not only for the gallery page, but also for others.

Why doesn't my replace attempt work? I am sure I have "–" in wp_get_document_title(), not "-".


Solution

  • The dash of wp_get_document_title() is a different charachter.

    Try this code somewhere in your page or in a plugin to see the difference:

    
    $title = wp_get_document_title();
    $bloginfo = get_bloginfo('name');
    
    echo '<div style="padding-left:20rem;"><pre>'; 
    
    var_dump ($title, htmlspecialchars($title));
    echo "\n\n";
    
    var_dump ($bloginfo, htmlspecialchars($bloginfo));
    echo '</pre></div>';
    

    The dash is quite probably &#8211; HTML code, also called &ndash;

    So you should use &#8211; instead of - in your str_replace