Javascript String Length Differs From PHP mb_strlen

前端 未结 4 2056
失恋的感觉
失恋的感觉 2020-12-10 16:11

I use document.getElementById(\"text\").value.length to get the string length through javascript, and mb_strlen($_POST[\'text\']) to get the string

相关标签:
4条回答
  • 2020-12-10 16:30

    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!

    0 讨论(0)
  • 2020-12-10 16:30

    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?

    0 讨论(0)
  • 2020-12-10 16:36

    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.

    0 讨论(0)
  • 2020-12-10 16:54

    This should do the trick

    function mb_strlen (s) {
      return ~-encodeURI(s).split(/%..|./).length;
    }
    
    0 讨论(0)
提交回复
热议问题