Check if title has empty space in wordpress

How does one check if the title, generated by wp_title() has empty space in front of it? I have found how to trim it with trim()

<?php echo trim(wp_title('', false)); ?>

But, like with setting a wp_title() for home page, I’d like to put this in the functions.php file, so that it’s not in my header. So far I have

add_filter( 'wp_title', 'trim_wp_title' );
function trim_wp_title( $title ) {
    if( /* check if $title contains empty space */ ) {
        $title = echo trim(wp_title('', false));
    }
    return $title;
}

Related posts

Leave a Reply

2 comments

  1. You don’t really need to do the check at all, your function can be simplified down to:

    add_filter( 'wp_title', 'trim_wp_title' );
    function trim_wp_title( $title ) {
        return trim($title);
    }
    

    trim will just leave the string as it is if there’s nothing to trim off of it.

  2. Do you want something like this?

    $string = " Here is a leading space";
    if (substr($string, 0, 1) === ' ')  {
        echo 'Yes, i have leading space';
    }