-1

I am making a quiz website where german is the main language. in PHP, When i count this text => "(ä, ö, ü and ß)", it return total 19 chars but in Javascript (in browser) it count as 15.

//- PHP
strlen("(ä, ö, ü and ß)"); // - returns 19
//- JS
"(ä, ö, ü and ß)".length; //- return 15

I need to make them equal. is it possible?

Md Arif Islam
  • 57
  • 2
  • 6
  • `strlen()` returns the number of bytes rather than the number of characters in a string. Please read the official guide [link](https://www.php.net/manual/en/function.strlen.php) – Simone Rossaini May 27 '21 at 13:26
  • "***Note:** `strlen()` returns the number of bytes rather than the number of characters in a string.*" from [the PHP documentation](https://www.php.net/manual/en/function.strlen.php). So, what do you want to do - count the bytes in JS or count the characters in PHP? – VLAZ May 27 '21 at 13:26
  • Hints: The length property of a String object in Javascript contains the length of the string, in UTF-16 code units, `strlrn` function in PHP returns the number of bytes rather than the number of characters in a string. – Zhorov May 27 '21 at 13:27

2 Answers2

2

How i write in the comment strlen will return number of bytes instead you can use mb_strlen like:

echo mb_strlen("(ä, ö, ü and ß)", 'utf8'); // output 15

Link:

Simone Rossaini
  • 8,115
  • 1
  • 13
  • 34
0

Use TextEncoder Javascript native API to convert the string from UTF-16 to UTF-8 format and then get the length as bytes.

var encodedText = new TextEncoder().encode("(ä, ö, ü and ß)");
console.log(encodedText.length);

Please note it does not work in IE. Refer TextEncoder

AB Udhay
  • 643
  • 4
  • 9