Skip to content
Advertisement

mb_strlen() counts new lines twice – difference to .length() in JavaScript

I have this issue since we try to count the characters in a textarea field by JavaScript and to validate the character count with PHP. The problem appears when in the textarea a text is filled in with newlines.

For counting in JavaScript we use without an changes of the input text (white spaces removing for example):

JavaScript

In PHP we do the counting with mb_strlen() and tested it with setting the encoding and without:

JavaScript

Example text:

JavaScript

This text leads to a character count of 424 both in JavaScript and PHP.

When I enter a new line (before Donec quam felis,)

JavaScript

the characters count in JavaScript is 425, in PHP it is 426. My goal is to get the same counting in PHP as for me and the user a new line should not be counted twice.

Advertisement

Answer

I think PHP is counting a newline as n. The easy way is to count the number of occurrences in the string and subtract if from the length:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement