0

I'm using the following function to replace the default functionality of the the_title() method in my WordPress homepage. My goal was to limit the number of characters so that the post boxes on my homepage are the same height.

function the_title_limit($length, $replacer = "...") {

    $charset = 'UTF-8';
    $string = the_title("","",FALSE);

    if(mb_strlen($string, $charset) > $length) {
        $string = (preg_match("/^(.*)\W.*$/", mb_substr($string, 0, $length+1, $charset), $matches) ? $matches[1] : mb_substr($string, 0, $length, $charset)) . $replacer;
    }

    echo $string;
}

It seems to be working, however, the website uses Cyrillic alphabet, so I believe there is something else I must do so I don't get the strange symbols at the end of the string with some of the posts - �

I'm calling the function with different values for $length (100, 101, 102) but I still get the symbol at the end of some titles. I guess I'm missing something in regards to how Cyrilic letters would be counted and I'm not sure what.

EDIT: I was already advised to replace strlen() and substr() with mb_strlen() and mb_substr() but now the symbol appears on the titles I didn't have it before and vice versa. One thing to note is that it appears on titles containing both Cyrilic and Latin letters.

Can someone provide any solution/workaround to remove this symbol?

  • 1
    have a look at [multibyte string functions](https://www.php.net/manual/en/ref.mbstring.php) – berend Mar 07 '21 at 09:10
  • 1
    your string may be unicode string, use mb_substr(), mb_strlen() – Anurat Chapanond Mar 07 '21 at 09:12
  • 1
    As already mentioned, but from the duplicate - https://stackoverflow.com/a/3161869/1213708 – Nigel Ren Mar 07 '21 at 09:12
  • I tried replacing strlen() and substr() with mb_strlen() and mb_substr(), but now, the symbol appeared on the titles that didn't have it before and was removed from the ones that had it. What is interesting is that now it appears on the title that has both Cyrilic and Latin letters. – Todor Atanasov Mar 07 '21 at 09:18

0 Answers0