Skip to content

Counting Characters: PHP vs Javascript

On a recent project, an issue cropped up where we were exporting xml
reports to a third party, who had rules about line lengths in
Description fields.

So, I wrote up a quick-and-dirty character counter for the description
field so the client can keep their descriptions under the 1500-word
limit.

Here’s how it was done:

Now the html and javascript:

All was working well, except I underestimated the descriptions. The next
morning, the thing was broken. The php side was kicking validation
errors (“over 1500 characters”), while the javascript was counting a
mere 1480. Why?

Turns out the data was full of bullets and other multibyte characters.
To make the counts match, I needed multibyte-safe php:

Hooray! Now the counts match!