Home » Php » Javascript String Length Differs From PHP mb_strlen

Javascript String Length Differs From PHP mb_strlen

Posted by: admin July 12, 2020 Leave a comment

Questions:

I use document.getElementById("text").value.length to get the string length through javascript, and mb_strlen($_POST['text']) to get the string length by PHP and both differs very much. Carriage returns are converted in javascript before getting the string length, but I guess some characters are not being counted.

For example,

[b]15. Umieszczanie obrazka z logo na stronie zespołu[/b]

This block of text is calculated 57 in javascript and 58 in PHP. When the text gets long, the difference increases. Is there any way to overcome this?

How to&Answers:

If you’re trying to get the length of an UTF-8 encoded string in PHP, you should specify the encoding in the second parameter of mb_strlen, like so:

mb_strlen($_POST['text'], 'UTF-8')

Also, don’t forget to call stripslashes on the POST-var.

Answer:

I have found an mb_strlen equivalent function for Javascript, maybe this might be useful for someone else:

function mb_strlen(str) {
    var len = 0;
    for(var i = 0; i < str.length; i++) {
        len += str.charCodeAt(i) < 0 || str.charCodeAt(i) > 255 ? 2 : 1;
    }
    return len;
}

Thanks to all that tried to help!

Answer:

This should do the trick

function mb_strlen (s) {
  return ~-encodeURI(s).split(/%..|./).length;
}

Answer:

I notice that there is a non-standard character in there (the ł) – I’m not sure how PHP counts non-standard – but it could be counting that as two. What happens if you run the test without that character?