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):

input.val().length

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

$length = mb_strlen($elements['#value'], 'UTF-8');
$length2 = mb_strlen($elements['#value']);

Example text:

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo.

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

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

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.
Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo.

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:

$newLines = substr_count($text, "n");

$length = mb_strlen($elements['#value']) - $newLines;
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement