Let’s say that I have an entry titled Crime & Punishment
I tried to count the number of characters of my entry titles using the following line:
echo strlen( get_the_title() );
I expected the code would give me 18 characters for Crime & Punishment, but the result turned out to be 23 characters.
The code above didn’t give me my desired result since it reads the symbols within the title as a HTML code. Is there any workaround for such case?
2 Answers
There are actually two problems:
-
The
&
is encoded as&
, so you have to usehtml_entity_decode()
first. -
Multi-byte characters need more than one byte, and
strlen()
will fail with them. Don’t use strlen().
So use something like this:
$title = html_entity_decode( get_the_title(), ENT_XML1, 'UTF-8' );
$length = mb_strlen( $title, 'utf-8' );