Reputation: 1763
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?
Upvotes: 9
Views: 8317
Reputation: 1348
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 area
var value = eval('CKEDITOR.instances.'+id+'.getData();');
// String length without the CRLF
var taille = value.length;
// get number of line
var nb_lines = (value.match(/\n/g) || []).length;
// Now, this value is the same you'll get with strlen in PHP
taille = taille + nb_lines;
Upvotes: 0
Reputation: 9859
This should do the trick
function mb_strlen (s) {
return ~-encodeURI(s).split(/%..|./).length;
}
Upvotes: 0
Reputation: 1763
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!
Upvotes: 2
Reputation:
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.
Upvotes: 3
Reputation: 4841
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?
Upvotes: 0