Problem using substr in text with PHP

Question:

When using substr in a variable with text, it is returning a special character "�" could someone help me?

I'm using the following code:

$excerpt = get_the_content();
$excerpt = strip_shortcodes($excerpt);
$excerpt = strip_tags($excerpt);
$the_str = substr($excerpt, 0, 335);
echo $the_str . '...'; 

Answer:

Your string is probably encoded as UTF-8, which is desirable, as you can represent a huge amount of special characters. In UTF-8, certain characters, including all accents, take up more than one byte. However, the substr function considers that each character occupies only one byte. What is happening is that the substr is cutting a character in half, taking only the first byte of it. When the browser will display the output of substr , this single byte is considered an invalid character.

The solution is to use the mb_substr function, which is designed to handle multibyte characters:

$the_str = mb_substr($excerpt, 0, 335);
Scroll to Top