Skip to content Skip to sidebar Skip to footer

Javascript String Length Differs From Php Mb_strlen

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

Solution 1:

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

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

Thanks to all that tried to help!

Solution 2:

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?

Solution 3:

This should do the trick

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

Solution 4:

Just type more than one line in your text area and you'll see the diference going bigger and bigger... This came from the fact Javascript value.length don't count the end of line when all PHP length functions take them in account. Just do:

// In case you're using CKEditot// id is the id of the text areavar value = eval('CKEDITOR.instances.'+id+'.getData();');

// String length without the CRLF   var taille = value.length;

// get number of linevar nb_lines = (value.match(/\n/g) || []).length;

// Now, this value is the same you'll get with strlen in PHP
taille = taille + nb_lines;

Post a Comment for "Javascript String Length Differs From Php Mb_strlen"